Skip to content

Instantly share code, notes, and snippets.

@capnmidnight
Last active August 29, 2015 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capnmidnight/73b5a9c59da735be0d6c to your computer and use it in GitHub Desktop.
Save capnmidnight/73b5a9c59da735be0d6c to your computer and use it in GitHub Desktop.
Javascript named arguments
// so named because why the hell not?
function banquo(func) {
var def = func.toString();
// find the comma-delimeted list of parameters
var params = def.match(/\(\s*(\w+(\s*,\s*\w+)*)\s*\)/)[1].split(',').map(function (p) {
return p.trim();
});
// extract out just the function body
var body = def.match(/\{((.|\n)+)\}/g)[0];
body = body.substring(1, body.length - 1).trim();
// this is recursive and would be better done iteratively, but I got bored
function buildScript(ps) {
var script = "{";
for (var i = 0, l = ps.length; i < l; ++i) {
var leftover = ps.slice();
var p = leftover.splice(i, 1);
if (i > 0) {
script += ",";
}
script += p + ":function(" + p + "){";
if (leftover.length > 0) {
script += "return " + buildScript(leftover, body);
}
else {
script += body;
}
script += "}";
}
script += "}";
return script;
}
// at least a modicum of avoiding polluting the global scope
var state = {obj: null};
with (state) {
eval("var obj = " + buildScript(params));
}
return state.obj;
}
var something = banquo(function (a, b, c, d) {
console.log("A: ", a, ", B: ", b, ", C: ", c, ", D:", d);
});
something.a(1).b(2).c(3).d(4);
something.b(1).a(2).c(3).d(4);
something.a(1).c(2).b(3).d(4);
something.b(1).c(2).a(3).d(4);
something.c(1).a(2).b(3).d(4);
something.c(1).b(2).a(3).d(4);
something.a(1).b(2).d(3).c(4);
something.b(1).a(2).d(3).c(4);
something.a(1).c(2).d(3).b(4);
something.b(1).c(2).d(3).a(4);
something.c(1).a(2).d(3).b(4);
something.c(1).b(2).d(3).a(4);
something.a(1).d(2).b(3).c(4);
something.b(1).d(2).a(3).c(4);
something.a(1).d(2).c(3).b(4);
something.b(1).d(2).c(3).a(4);
something.c(1).d(2).a(3).b(4);
something.c(1).d(2).b(3).a(4);
something.d(1).a(2).b(3).c(4);
something.d(1).b(2).a(3).c(4);
something.d(1).a(2).c(3).b(4);
something.d(1).b(2).c(3).a(4);
something.d(1).c(2).a(3).b(4);
something.d(1).c(2).b(3).a(4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment