Skip to content

Instantly share code, notes, and snippets.

@redbluish
Created December 1, 2013 17:09
Show Gist options
  • Select an option

  • Save redbluish/7736861 to your computer and use it in GitHub Desktop.

Select an option

Save redbluish/7736861 to your computer and use it in GitHub Desktop.
variadic.js
;(function (window, undefined) {
var _slice = Array.prototype.slice;
function variadic(fn) {
var numParams = fn.length, // 形参个数
numNamedArgs = numParams - 1;
return numParams < 1 ? fn : function () {
var
numArgs = arguments.length, // 实参个数
namedArgs = _slice.call(arguments, 0, numNamedArgs),
numMissingNamedArgs = Math.max(0, numNamedArgs - numArgs),
argPadding = Array(numMissingNamedArgs),
variadicArgs = _slice.call(arguments, numNamedArgs);
return fn.apply(this, namedArgs
.concat(argPadding)
.concat([variadicArgs]));
};
}
window.variadic = variadic;
}).call(this, this);
function unary(first) {
return first;
}
function binary(first, rest) {
return [first, rest];
}
// output: ['why', 'hello', 'there']
variadic(unary)('why', 'hello', 'there');
// output: ['why', ['hello', 'there']]
variadic(binary)('why', 'hello', 'there');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment