I am learning curry function in javascript. And a question occurs to me.
// how to implement the add function in the below.
add(1)(2)(3) = 6;
add(1, 2, 3)(4) = 10;
add(1)(2)(3)(4)(5) = 15;
I've known the implemented code
function add() {
var _args = Array.prototype.slice.call(arguments);
var _adder = function () {
_args.push(...arguments);
return _adder;
};
_adder.toString = function () {
return _args.reduce(function (a, b) {
return a + b;
});
}
return _adder;
}
console.log(add(1)(2)(3)(4)(5)) // function
console.log(add(1)(2)(3)) // function
console.log(add(1, 2, 3)(4)) // function
console.log(add(1)(2)(3)(4)(5) == 15) // true
console.log(add(1)(2)(3) == 6) // true
console.log(add(1, 2, 3)(4) == 10) // true
console.log(add(1)(2)(3)(4)(5) === 15) // false
console.log(add(1)(2)(3) === 6) // false
console.log(add(1, 2, 3)(4) === 10) // false
I know how the implemented code works. But I am very curious about the question. From my view, " add(1)(2)(3) = 6; " means that after executing the expression "add(1)(2)(3)", it should return a value which is fully equals to Number 6. But from this question and its implement codes, I may have a misunderstanding about the question. SO, what does the question REALLY mean? This question is often asked by the interviewer.