Dynamic currying and how to hold both function and value in a JavaScript variable

I am learning JavaScript, and recently I ran into a problem that asked me to build a function that could generate output as follows:

var threeSum= sum(3);
threeSum //3
threeSum(4) //7
threeSum(4)(3) //10
threeSum(4)(3)(7) //17
threeSum(4)(3)(7)()(2) //19
threeSum - 2 //1
threeSum + 2 //5

I assume currying is involved, and I think I have a basic understanding of how currying works in a simple way, something like

a=>b=>c=> a+b+c

but I have no idea how I create a curry function that can handle an indefinite number of inputs, and how to make it so that it can lead to a variable that can act as a value and function.

Any insight appreciated! I just need a push in the right direction - at this moment I don’t even know what I'm looking for.

+4
2

, valueOf, javascript (, )

var valueAndCallable = function(x) {
    var res = function(a) { return a + x };
    res.valueOf = function() { return x; };
    return res;
};

var v = valueAndCallable(1)
console.log(v);      // function ... -
console.log(+v);     // 1 - calls .valueOf()
console.log(1 + v);  // 2 - calls .valueOf()
console.log(v(3));   // 4
Hide result

currying , res() valueAndCallable.

+3

, , .

, ​​:

const curryN = n => f => {
  let next = (m, acc) => x => m > 1 ? next(m - 1, acc.concat([x])) : f(...acc, x);
  return next(n, []);
};

const sum = (...args) => args.reduce((acc, x) => acc + x, 0);

sum(1, 2, 3, 4, 5); // 15
curryN(5)(sum)(1)(2)(3)(4)(5); // 15

let sum3 = curryN(3)(sum);
sum3(1)(2)(3); // 6

let sum5plusX = curryN(2)(sum)(5);
sum5plusX(6); // 11

. Array.reduce. currying. .

+1