Created
August 8, 2011 15:47
-
-
Save mazelife/1132000 to your computer and use it in GitHub Desktop.
A thing you can do with javascript's function.length
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
// Implementation of the router pattern using function.length | |
var add_two_things = function(a, b) { | |
return a + b | |
} | |
var add_three_things = function(a, b, c) { | |
return a + b + c | |
} | |
var get_router = function() { | |
// The user doesn't need to know which function they need to add | |
// 2 things vs. 3 things: they just want a single function they can pass 2 or 3 | |
// numbers to... | |
var arg_map, router, i; | |
arg_map = {} | |
for (i = 0; i < arguments.length; i++) { | |
arg_map[arguments[i].length] = arguments[i]; | |
} | |
router = function() { | |
var num_args, args; | |
num_args = arguments.length | |
if (arg_map[num_args]) { | |
// Convert arguments to an array. | |
args = Array.prototype.slice.call(arguments, 0); | |
return arg_map[num_args].apply(window, args); | |
} | |
} | |
return router; | |
} | |
add_router = get_router(add_two_things, add_three_things) | |
alert(add_router(2,3)); | |
alert(add_router(2,3,4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment