Skip to content

Instantly share code, notes, and snippets.

@ArnaudBuchholz
Created January 13, 2015 20:56
Show Gist options
  • Save ArnaudBuchholz/01f8d6152735384c2ae5 to your computer and use it in GitHub Desktop.
Save ArnaudBuchholz/01f8d6152735384c2ae5 to your computer and use it in GitHub Desktop.
Clone a function definition
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