Skip to content

Instantly share code, notes, and snippets.

@farskid
Created November 17, 2020 11:58
Show Gist options
  • Save farskid/66efdc2ace8e0fa5520e519b6efa61c8 to your computer and use it in GitHub Desktop.
Save farskid/66efdc2ace8e0fa5520e519b6efa61c8 to your computer and use it in GitHub Desktop.
overloading Javascript functions, unlimited sum
function unlimitedAdd(...nums) {
const func = unlimitedAdd;
func.sum = nums.reduce((total, current) => total + current, 0) + (func.sum || 0);
func.done = function() {
return func.sum;
}
return func;
}
let a = unlimitedAdd(1,2,3);
console.log(a.done())
a = a(4,5);
console.log(a.done())
a = a(6,7,8);
console.log(a.done())
a = a(14);
console.log(a.done())
@Fabsforce
Copy link

That's really a beautiful and very smart code indeed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment