https://bigfrontend.dev/problem/create-a-sum
Create a sum(), which makes following possible
const sum1 = sum(1);
sum1(2) == 3; // true
sum1(3) == 4; // true
sum(1)(2)(3) == 6; // true
sum(5)(-1)(2) == 6; // true/**
* @param {number} num
*/
function sum(num) {
// Declare a function which will be returned by
// the function sum(), so we can take a new number.
const func = function (newNum) {
// Add the new number to the previous one, call sum()
// and pass the result as argument, so we can take a
// new number again.
return sum(num + newNum);
};
// Override func's native valueOf function with our custom one that
// returns the current num, so we can do 'sum(1)(2)(3) == 6'.
// When encountering an object where a primitive value is expected,
// JavaScript calls valueOf method to convert the object (in js, functions are objects )
// to a primitive value.
// Besides valueOf, JavaScript also has toString to do such 'type coercion'.
// sum(1)(2)(3) === 6 will result in false, because '===' does not perform
// type conversion.
func.valueOf = function () {
return num;
};
return func;
}