Write a JavaScript curry function to add n numbers
Curry function uses JavaScript closure concepts. JavaScript closure remembers the previous lexical scope. Using the closure concepts we can write a JavaScript curry function to add n numbers. Following is an example:
function add(a) { let callback = function (b) { a += b; return callback; }; callback.toString = () => a; return callback; }; console.log(+add(1)(2)); // Output: 3
If we want every consecutive call to increment by we can use the following code:
function add() { let sum = 1; let callback = function (b) { sum++; return callback; }; callback.toString = () => sum; return callback; }; console.log(+add()()); // Output: 2 console.log(+add()()()); // Output: 3
https://stackoverflow.com/questions/33901793/writing-a-curried-javascript-function-that-can-be-called-an-arbitrary-number-of