vendredi 29 août 2014

Puzzle: JS Function that returns itself until there are no arguments


Vote count:

0




I'm trying to solve a puzzle, and am at my wit's end trying to figure it out.


I'm supposed to make a function that works like this:



add(1); //returns 1
add(1)(1); //returns 2
add(1)(1)(1); //returns 3


I know it can be done because other people have successfully completed the puzzle. I have tried several different ways to do it. This is my most recent attempt:



function add(n) {
//Return new add(n) on first call
if (!(this instanceof add)) {
return new add(n);
}

//Define calc function
var obj = this;
obj.calc = function(n) {
if (typeof n != "undefined") {
obj.sum += n;
return obj.calc;
}

return obj.sum;
}

//Constructor initializes sum and returns calc(n)
obj.sum = 0;
return obj.calc(n);
}


The idea is that on the first call, a new add(n) is initialized and calc(n) is run. If calc receives a parameter, it adds n to sum and returns itself. When it eventually doesn't receive a parameter, it returns the value of sum.


It makes sense in theory, but I can't get it to work. Any ideas?



asked 1 min ago







Puzzle: JS Function that returns itself until there are no arguments

Aucun commentaire:

Enregistrer un commentaire