Skip to content

Instantly share code, notes, and snippets.

@jhartikainen
Created November 26, 2009 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhartikainen/243557 to your computer and use it in GitHub Desktop.
Save jhartikainen/243557 to your computer and use it in GitHub Desktop.
var fun = String(fnc);
//Capture function args and body into capture groups
var argsBody = fun.match(
/^function[^(]*\(([^)]*)\)\s*{([\s\S]*)}$/
);
//Get argument names
var argNames = argsBody[1].split(/\s*,\s*/g);
//Function body
var body = argsBody[2];
//Replace arguments with provided values
var argumentValues = Array.prototype.slice.call(arguments, 1);
for(var i = 0; i < argumentValues.length; i++) {
body = body.replace(new RegExp(argNames[i], 'g'), argumentValues[i]);
}
var remainingArguments = argNames.slice(i);
return new Function(remainingArguments.join(','), body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment