2

javascript question to add infinite numbers, without empty parenthesis at the end

I've tried this:

const Sum = function (a) {
        function innerFunc (b) {
            console.log("B", b)
            return b ? Sum(a + b) : a;
        }
    }
  console.log(Sum(2)(3)(4))

but it works for console.log(Sum(2)(3)(4)()) ie an empty parenthesis in the end, is there a way to do it by changing the function so that console log without empty parenthesis gives the correct result, currently it throws an error stating Sum is not a function

abc xyz
  • 21
  • 2
  • No that's obviously impossible. You can return either a function or a number, but not both. – mousetail Nov 30 '22 at 10:00
  • 2
    You can do it by overriding the `toString` of the inner function which gets returned. Check the duplicate – adiga Nov 30 '22 at 10:07

1 Answers1

5

You could implement toString and use it in a function which needs a string.

function add(...args) {
    let total = 0;
    
    function sum (...args) {
        total += args.reduce((a, b) => a + b, 0);
        return sum;
    }

    sum.toString = function () {
        return total;
    }

    return sum(...args);
}

console.log(add(1, 2, 3));                //  6
console.log(add(1)(2)(3));                //  6
console.log(add(1, 2)(2)(3));             //  8
console.log(add(1, 6)(2, 2)(3));          // 14
console.log(add(1, 6)(2, 2)(3, 4, 5, 7)); // 30

A more advanced version could use the function for calcultions as well with Symbol.toPrimitive

function add(...args) {
    let total = 0;
    
    function sum (...args) {
        total += args.reduce((a, b) => a + b, 0);
        return sum;
    }

    sum[Symbol.toPrimitive] = function (hint) {
        return (['string', 'default'].includes(hint))
            ? total
            : sum;
    };

    return sum(...args);
}

console.log(add(1, 2, 3));                //  6
console.log(add(1)(2)(3));                //  6
console.log(add(1, 2)(2)(3));             //  8
console.log(add(1, 6)(2, 2)(3));          // 14
console.log(add(1, 6)(2, 2)(3, 4, 5, 7)); // 30
console.log(add(1, 2)(3, 4) + 32);        // 42
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392