Skip to content

Instantly share code, notes, and snippets.

@safareli
Created September 16, 2020 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safareli/ee8ecdf8aeb20616733a3b344af4b98d to your computer and use it in GitHub Desktop.
Save safareli/ee8ecdf8aeb20616733a3b344af4b98d to your computer and use it in GitHub Desktop.
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
Copy link

nodech commented Sep 16, 2020

function sum(...args) {
  const fn = sum.bind(sum, ...args);

  fn[Symbol.toPrimitive] = () => {
    return args.reduce((p, v) => p + v, 0);
  };

  return fn;
}

@atesgoral
Copy link

atesgoral 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)

@atesgoral
Copy link

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)
});

@safareli
Copy link
Author

safareli commented Jun 9, 2021

@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