I'm trying to write a sum function that does the following:
sum(1)(2)(3) => returns 6
However, I am having hard time with my solution. I know i'm making a silly mistake, can someone point me in the right direction?
My Implementation:
function add(args) {
let sum = args[0];
let func = function(...args2) {
if (!args2[0]) return sum;
sum += args2[0];
return func;
}
return func;
}
add(1)(2)(3);
Additionally, can I write a generic function that does the following? add(1)(2)(3) or add (1)(2)(3) () => 6
To have an arbitrary amount of calls, all which take a number, you'd need the return value to behave both as a function and a number depending. So that:
const five = add(2)(3);
console.log(five(10)); // behaves like a function
console.log(five + 10); // behaves like a number
I can't think of anyway to do that (or if there's a good reason one should do that) other than what I'd call a hack.
With that said, for fun I was able to do the following by abusing valueOf():
const add = (num1) => {
const func = (num2) => add(num1 + num2);
func.valueOf = () => num1;
return func;
}
console.log(add(1)(2)(3)); // *logs function* [output varies by environment]
console.log(add(1)(2)(3) + 10); // 16
console.log(add(1)(2) + 10); // 13
console.log(add(1) + 10); // 11
console.log(add(1)(2)(3) == 6); // true
console.log(add(1)(2)(3) === 6); // false
console.log(typeof add(1)(2)(3)); // function
console.log(typeof (add(1)(2) + 3)); // number
But that's obviously not very kosher.
Edit: Switched from using toString() to valueOf() per @PatrickRoberts's comment.
Recursion anyone? 😂
function add(n) {
return function(m) {
if (isNaN(m)) return n;
return add(n + m);
};
}
// add(1)(2)(3)() => 6
// add(1)(2)(3)("")() => "6"
// add(1)("2")(3)() => "123"
// functional one liner
const add = n => m => isNaN(m) ? n : add(n + m);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With