Skip to content

Instantly share code, notes, and snippets.

@tincho
Created December 6, 2018 14:53
Show Gist options
  • Save tincho/f39c54c4ea18ca7cda3f2bbcce7b511b to your computer and use it in GitHub Desktop.
Save tincho/f39c54c4ea18ca7cda3f2bbcce7b511b to your computer and use it in GitHub Desktop.
ES5 vs ES6 function for fix a function to take up to N-arguments (see N-ary or arity)
// pre-ES6
function _ary(fn, arity) {
arity = arity || 1;
return function() {
// could use Array.from(arguments).slice(0, arity) ?
var args = Array.prototype.slice.call(arguments, 0, arity);
return fn.apply(null, args);
};
}
// ES6 version... lovely!
const _ary = (fn, arity = 1) => (...args) => fn(...args.slice(0, arity));
// try it:
var log1 = _ary(console.log);
var log3 = _ary(console.log, 3);
log1("will", "only", "take", "the first");
// output: will
log3("will", "only", "take 3 arguments", "and ignore all", "the others");
// output: will only take 3 arguments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment