Categories
interview

Currying

Breaking down a function into a series of function calls with an argument. The following is an Javascript ES6 example of a sum function that returns the sum of the calls until no argument is passed.

Code

const sum = (val) => {
  let total = 0;
  if (val === undefined) {
    return total;
  }
  total = val;
  const ret = (x) => {
    if (x === undefined) {
      return total;
    }
    total += x;
    return ret;
  };
  return ret;
};

console.log(sum(5)(6)(0)(-1)()); // 10

Demo