Skip to content

Instantly share code, notes, and snippets.

@nasser
Last active August 29, 2015 14:01
Show Gist options
  • Save nasser/dbe32a106edf7deb9a8d to your computer and use it in GitHub Desktop.
Save nasser/dbe32a106edf7deb9a8d to your computer and use it in GitHub Desktop.
function namedArgs(fn) {
var names = fn.toString().match(/function.*\(([^\)]+)\)/)[1].split(',');
return eval("(function(args) {\
return fn(" + names.map(function(n) { return "args[\"" + n.trim() + "\"]"}).join() + ");\
})");
}
@nasser
Copy link
Author

nasser commented May 17, 2014

Converts a javascript function using traditional positional arguments to use named arguments from an object. Argument names are taken from the original declaration.

var ellipse = function(x, y, w, h) {
  // draw ellipse
}

ellipse(30, 40, 10, 20);
ellipse = namedArgs(ellipse);
ellipse({x:20, y:40, w:10, h:20});

Or from coffeescript

ellipse 30, 40, 10, 20
ellipse = namedArgs ellipse
ellipse x:30, y:40, w:10, h:20

@OmerShapira
Copy link

Wow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment