Created
September 16, 2020 14:30
-
-
Save safareli/ee8ecdf8aeb20616733a3b344af4b98d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sum(1, 2, 3, 4) == 10 // true | |
sum(1, 2, 3, 4)(1, 2, 3, 4) == 20 // true | |
sum(1)(2)(3)(4)(1)(2)(3)(4) == 20 // true | |
function sum(...args) { | |
function res(...args2) { | |
return sum(_sum(args), _sum(args2)) | |
} | |
// https://javascript.info/object-toprimitive | |
res[Symbol.toPrimitive] = () => _sum(args) | |
return res | |
} | |
function _sum(arr) { | |
return arr.reduce((a,b) => a + b, 0) | |
} |
nodech
commented
Sep 16, 2020
Golfing Nodar's solution a bit:
function sum(...args) {
const fn = sum.bind(sum, ...args);
fn[Symbol.toPrimitive] = () => args.reduce((p, v) => p + v);
return fn;
}
(No need to pass 0
as the second argument to reduce
when you're just adding all items -- the first item will be passed in as the first accumulator value to the reducer)
And further golfing for the heck of it:
const sum = (...args) => Object.assign(sum.bind(sum, ...args), {
[Symbol.toPrimitive]: () => args.reduce((p, v) => p + v)
});
@atesgoral if you don't pass in 0
sum() == 1
// Uncaught TypeError: Reduce of empty array with no initial value
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment