Created
December 1, 2013 17:09
-
-
Save redbluish/7736861 to your computer and use it in GitHub Desktop.
variadic.js
This file contains hidden or 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
| ;(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