Created
July 10, 2013 18:02
-
-
Save stash/5968609 to your computer and use it in GitHub Desktop.
Wrap a function to have a specify "arity" (`.length`)
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
| /** | |
| * Wrap a function so that it has `.length` (a.k.a "arity") n. | |
| * | |
| * Any additional parameters are dropped before the wrapped function is called. | |
| * | |
| * @param {int} n number of parameters on the wrapper. | |
| * @param {function} fn function with arbitrary signature. | |
| * @return {function} wrapper | |
| */ | |
| exports.arity = function(n, fn) { | |
| switch(n) { | |
| case 0: return function() { | |
| return fn.call(this); | |
| }; | |
| case 1: return function(a) { | |
| return fn.call(this,a); | |
| }; | |
| case 2: return function(a,b) { | |
| return fn.call(this,a,b); | |
| }; | |
| case 3: return function(a,b,c) { | |
| return fn.call(this,a,b,c); | |
| }; | |
| case 4: return function(a,b,c,d) { | |
| return fn.call(this,a,b,c,d); | |
| }; | |
| case 5: return function(a,b,c,d,e) { | |
| return fn.call(this,a,b,c,d,e); | |
| }; | |
| default: | |
| throw new TypeError('Only up to airity 5 is implemented'); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment