Skip to content

Instantly share code, notes, and snippets.

@NothingEverHappens
Created December 2, 2012 00:57
Show Gist options
  • Save NothingEverHappens/4186236 to your computer and use it in GitHub Desktop.
Save NothingEverHappens/4186236 to your computer and use it in GitHub Desktop.
AllowArrays
/**
* Author: Kirill Cherkashin
*
* Before:
* a(1);
* a(2);
* a(3);
* a(4);
* Now:
* var b = AllowArrays( a, 0 ); //We do it with the first argument, but we can have more comma-separated
* b([1,2,3,4]);
*
*/
var a = function(){
console.log( arguments);
};
var acceptArrays = function( ){
var args = Array.prototype.slice.call(arguments);
var func = args.shift();
var firstArg = args.shift();
if( typeof firstArg !== "number"){
return func;
}
return function(){
var new_func, new_args;
args.unshift( func );
var argument = arguments[firstArg];
if( typeof argument === "object"){
for( var i in argument) {
if( argument.hasOwnProperty(i)){
new_func = acceptArrays.apply( null, args );
new_args = Array.prototype.slice.call(arguments);
new_args[firstArg] = argument[i];
new_func.apply( this, new_args );
}
}
} else {
new_func = acceptArrays.apply( null, args );
new_func.apply( this, arguments );
}
};
}
var b = acceptArrays( a, 0 );
b(0,1);
b([0,1],"first");
var c = acceptArrays( a, 1 );
c(0,1);
c(0,[1,2]);
var d = acceptArrays( a, 0, 1 );
d([1,2],[3,4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment