Skip to content

Instantly share code, notes, and snippets.

@wentout
Created August 13, 2020 14:30
Show Gist options
  • Select an option

  • Save wentout/1915790d4b4d2d7d004d46659b903cf2 to your computer and use it in GitHub Desktop.

Select an option

Save wentout/1915790d4b4d2d7d004d46659b903cf2 to your computer and use it in GitHub Desktop.
Summ With Arity
const summ = function (...args) {
let arity = 0;
let storage = [];
const isNumber = (el) => {
return (this instanceof Number) || typeof el === 'number' && !Number.isNaN(el);
};
if (isNumber(this)) {
arity = 0 + this;
} else if (this instanceof Object) {
if (
typeof this.arity === 'number' &&
!Number.isNaN(this.arity) &&
this.arity > 0
) {
arity = this.arity;
}
if (Array.isArray(this.storage)) {
storage = this.storage.slice();
}
}
if (arity === 0) {
return 0;
}
if (args.length) {
args.forEach(el => {
if (
isNumber(el) &&
storage.length < arity
) {
storage.push(el);
}
});
}
if (storage.length < arity) {
return summ.bind({
arity,
storage
});
}
const result = storage.reduce((acc, el) => {
return acc + el;
}, 0);
return result;
};
sumArity5 = summ.call(5);
console.log('summ arity 5', sumArity5(1, 2, 3, 4, 5)); // 15
console.log('summ arity 5', sumArity5(2, 3, 4)(5, 6)); // 20
console.log('summ arity 5', sumArity5(3, 4)(5, 6)(7)); // 25
console.log('summ arity 5', sumArity5(4, 5)(6)(7, 8)); // 30
console.log('summ arity 5', sumArity5(5)(6)(7)(8)(9)); // 35
// summ arity 4
console.log('summ arity 4', summ.bind(4)(1, 2, 3)(4, 5)); // 10
console.log('defaults {arity : 5, storage: [1, 2, 3]}', summ.bind({
arity: 5,
storage: [1,2,3]
})(4, 5)); // 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment