ES5 vs ES6 function for fix a function to take up to N-arguments (see N-ary or arity)
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
// 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