B
B
Bogdan2018-08-02 20:34:45
JavaScript
Bogdan, 2018-08-02 20:34:45

Recursive currying?

Hello gentlemen gurus. Here I solve the problem of how to make recursive currying so that you can set a different number of arguments and function calls. It seems that everything worked out, but there is a nuance, if you run the function several times in a row, it returns the last value. If you run with timeouts, then everything is OK, can you tell me how to solve the problem, thanks.

const curring = (sum = 0, ...args) => {
  sum += args.reduce((a,b) => a+b, 0)
  curring.valueOf = () => sum
  return curring.bind(null, sum)
}

console.log(curring(1))
console.log(curring(1,2,5))
console.log(curring(1)(2,5))
console.log(curring(1)(2)(5,5)(5))

// 18
// 18
// 18
// 18

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2018-08-02
@bogdan_uman

The whole problem is that you override the valueOf method of the original function for each call, it is more correct to return a new function each time:

const curring = (...initArgs) => {
  let sum = 0;
  const curried = (...args) => {
    sum = args.reduce((a, b) => a + b, sum);
    return curried;
  };
  curried.valueOf = () => sum;
  return curried(...initArgs);
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question