Created
January 13, 2015 20:56
-
-
Save ArnaudBuchholz/01f8d6152735384c2ae5 to your computer and use it in GitHub Desktop.
Clone a function definition
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
function cloneFunction(functionToClone) { | |
functionToClone = functionToClone.toString(); | |
var paramStart = functionToClone.indexOf('('), | |
paramEnd = functionToClone.indexOf(')'), | |
paramList = functionToClone.substr(paramStart + 1, paramEnd - paramStart - 1).split(','), | |
bodyStart = functionToClone.indexOf('{'), | |
bodyEnd = functionToClone.lastIndexOf('}'), | |
body = functionToClone.substr(bodyStart + 1, bodyEnd - bodyStart - 1), | |
len, | |
idx, | |
parameter, | |
parameters = []; | |
len = paramList.length; | |
for (idx = 0; idx < len; ++idx) { | |
parameter = paramList[idx].trim(); | |
if (parameter) { | |
if (0 === idx) { | |
parameters.push('var '); | |
} else { | |
parameters.push(',\r\n '); | |
} | |
parameters.push(parameter); | |
parameters.push(' = arguments['); | |
parameters.push(idx); | |
parameters.push(']'); | |
} | |
} | |
if (parameters.length) { | |
parameters.push(';\r\n'); | |
body = parameters.join('') + body; | |
} | |
return new Function(body); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment