Last active
September 14, 2015 01:13
-
-
Save postpostscript/93bd924535a7a8272899 to your computer and use it in GitHub Desktop.
A simple javascript/coffeescript helper function to run different callbacks for different number of arguments
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
var variableArgs, | |
slice = [].slice; | |
variableArgs = function(callbacks) { | |
var defaultKey; | |
defaultKey = 'default'; | |
return function() { | |
var args, numArgs, ref; | |
args = 1 <= arguments.length ? slice.call(arguments, 0) : []; | |
numArgs = args.length || 0; | |
return ((ref = callbacks[numArgs]) != null ? ref : callbacks[defaultKey]).apply(null, args); | |
}; | |
}; |
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
variableArgs = (callbacks) -> | |
defaultKey = 'default' | |
(args...) -> | |
numArgs = args.length or 0 | |
(callbacks[numArgs] ? callbacks[defaultKey])(args...) |
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
var exampleFn = variableArgs({ | |
'1': function(arg) { | |
// Return the reverse of the argument | |
return String(arg).split("").reverse().join(""); | |
}, | |
'2': function(arg1, arg2) { | |
// Return the strings combined with a space in the middle | |
return String(arg1) + " " + String(arg2); | |
}, | |
'3': function(arg1, arg2, arg3) { | |
// Return the strings combined with the third in the middle | |
return String(arg1) + String(arg3) + String(arg2); | |
}, | |
'default': function() { | |
return String(); | |
} | |
}); | |
exampleFn("reverse me!"); | |
// => "!em esrever" | |
exampleFn("arg1", "arg2"); | |
// => "arg1 arg2" | |
exampleFn("arg1", "arg2", ", "); | |
// => "arg1, arg2" | |
exampleFn(); | |
// => "" | |
exampleFn("too", "many", "arguments", "will", "spoil", "the", "broth"); | |
// => "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment