Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Last active September 14, 2015 01:13
Show Gist options
  • Save postpostscript/93bd924535a7a8272899 to your computer and use it in GitHub Desktop.
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
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);
};
};
variableArgs = (callbacks) ->
defaultKey = 'default'
(args...) ->
numArgs = args.length or 0
(callbacks[numArgs] ? callbacks[defaultKey])(args...)
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