1

i am trying to implement my own custom sum function. The goal is to have a function called "sumFromTo" that takes 4 parameter * iteratorname * from * to * function

where "function" can be some other function and where the solution is to sum all. For example

// works 
  sumFromTo(i,1,10,i+1)  // = 65

But if i wrap this into an other function it will break, because mathjs doesn't know "x"

// works not because x is undefined
test(x) = sumFromTo(i,1,x,i+1) 
test(10)

My Import looks like this:

function sumFromTo(iteratorName, from, to, toString, f) {
    var total = 0;
    var toVal = typeof to == "number" ? to : to.length;
    for (var iterator = from; iterator <= toVal; iterator++) {
        mathScope[iteratorName] = iterator;
        mathScope[toString + "_" + iterator] = to[iterator];
        total += math.eval(f, mathScope);
    }
    return total;
}
sumFromTo.transform = function (args, math, scope) {
    /*   Iterator    */
    var iteratorName = "notfound";
    if (args[0] instanceof math.expression.node.SymbolNode) {
        iteratorName = args[0].name;
    } else {
        throw new Error('First argument must be a symbol');
    }

    /*    Startvalue of Iterator    */
    if (args[1] instanceof math.expression.node.ConstantNode) {
        if (args[1].value == 0) {
            throw new Error('Sum must counting from >=1: 0 given');
        }
    }

    /*    to: Array to loop    */
    if (args[2] instanceof math.expression.node.SymbolNode) {
        var toString = args[2].name;
    }

    /*    compile    */
    var from = args[1].compile().eval(scope);
    scope[iteratorName] = from;
    var to = args[2].compile().eval(scope);

    if (to.constructor.name == "Matrix") {
        to = to.toArray();
        scope[toString] = to;
    }else{
        if(typeof to == "object"){
            to = to.toArray();
        }
    }
    return sumFromTo(iteratorName, from, to, toString, args[3].toString());
};
sumFromTo.transform.rawArgs = true;
math.import({sumFromTo: sumFromTo}, {override: true});

I create a fiddle https://jsfiddle.net/o49p4zwa/2/ , maybe it's helpful to understanding my problem.

Does someone know what i am missing or what i am doing wrong?

Thanks in advance!!

jdoeName
  • 11
  • 1

1 Answers1

0

What you need is closure

test = function(x) {
    sumFromTo(i,1,x,i+1) 
}
test(10)
Maciej Caputa
  • 1,831
  • 12
  • 20
  • thx for your answer but i forgot to say, that this is a kind of math.js input. Its user generated and comes from the frontend. I can create a static function named "test" in my .js file. But thats not what i want.. i am looking for a dynamic way to define this function. – jdoeName Feb 02 '17 at 23:03