Created
June 26, 2013 20:08
-
-
Save zeekay/5871149 to your computer and use it in GitHub Desktop.
Why would anyone ever want to do this? Reasons...
This file contains hidden or 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
injectArgs = (func, args...) -> | |
rawFunc = func.toString() | |
argNames = (a.trim() for a in (/function \((.*)\)/.exec rawFunc)[1].split(',')) | |
func = rawFunc.replace /function \((.*)\)/, 'function anonymous()' | |
if args.length != argNames.length | |
throw new Error 'Function arity must match number of passed arguments' | |
unless args.length > 0 | |
return new Function func | |
argDeclarations = [] | |
for name in argNames | |
argDeclarations.push name + '=' + JSON.stringify args.shift() | |
new Function """ | |
var #{argDeclarations.join ','}; | |
return (#{func}).call(this); | |
""" | |
f = injectArgs (x, y, z) -> | |
console.log x, y, z | |
, 1, 2, 3 | |
console.log f.toString() | |
f() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment