Jeremy Iglehart Jeremy Iglehart - 4 months ago 8
Javascript Question

addNumbers(1)(2)(3)... How to call a function arbitrary number of times and have it add up?

Consider the following example:



function thisNumberWrapper(wrapperNumber) {
function multiply(anotherNumber) {
console.log(`This is your number: ${wrapperNumber} times another number: ${anotherNumber}: ${wrapperNumber * anotherNumber}`)
}
return multiply
}

let wrappedNumber = thisNumberWrapper(2)(4)





This works just fine... But what I would like to do is have a function that works like so:

addNumbers(1)(2)(3)(4)
and get back
10


Is this possible?

Obviously I've googled around and looked for this here on stackoverflow - but I can't find anything anywhere that has this pattern. I was working on a project a long time ago and we were using this type of "recursion" for a specific use case - I was looking to do that again.

Does anyone know how to pattern this out?




Edit: Getting closer





function addNumbers(number) {
console.log(number)
return addNumbers
}

addNumbers(1)(2)(3)(4)(5)(6)





But it's still not working.

Answer

implement valueOf & toString of Embedded Function

function multiply(x) {
    var result = x;  

    function f(y) { 
        result *= y;
        return f;
    }; 
    f.toString = function () { return result; }; // for expecting string, 1st log
    f.valueOf = function () { return result; };  // for expecting number, 2nd log

    return f;
}


console.log(
   multiply(4)(5)
)

console.log(
  multiply(5)(10)(2)(2)
)

Comments