Skip to content

Instantly share code, notes, and snippets.

@zeekay
Created June 26, 2013 20:08
Show Gist options
  • Save zeekay/5871149 to your computer and use it in GitHub Desktop.
Save zeekay/5871149 to your computer and use it in GitHub Desktop.
Why would anyone ever want to do this? Reasons...
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