Last active
August 29, 2015 14:14
-
-
Save capnmidnight/73b5a9c59da735be0d6c to your computer and use it in GitHub Desktop.
Javascript named arguments
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
// 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