Last active
August 29, 2015 14:23
-
-
Save cocoabox/4e90bd1c2156b8dcb8f1 to your computer and use it in GitHub Desktop.
python positional named arguments emulation using javascript
This file contains 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
"use strict"; | |
function get_args(arguments_) { | |
/* http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript */ | |
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; | |
var ARGUMENT_NAMES = /([^\s,]+)/g; | |
var src = arguments_.callee.toString().replace(STRIP_COMMENTS, ''); | |
var pars = src.slice(src.indexOf('(')+1, src.indexOf(')')).match(ARGUMENT_NAMES); | |
if (! pars) { pars = []; } | |
var i, j; | |
// enable "arg1", "arg2", {"arg5":"xxx"} | |
// where arg1, arg2 are positional arguments, arg5 is named arguments | |
var out = {}; | |
for (i = 0; i < pars.length; ++i) { | |
var argi = arguments_[i], | |
is_named_args = false; | |
if (typeof argi === "object"){ | |
is_named_args = true; | |
var argi_keys = Object.keys(argi), | |
pars_copy = JSON.parse(JSON.stringify(pars)), | |
wanted_keys = pars_copy.splice(i); | |
for (j = 0; j < argi_keys.length; ++j){ | |
if (wanted_keys.indexOf(argi_keys[j]) === -1) { | |
is_named_args = false; | |
break; | |
} | |
} | |
} | |
if (is_named_args) { | |
var named_args = argi; | |
for (j = i; j < pars.length; ++j) { | |
out[pars[j]] = named_args[pars[j]]; | |
} | |
break; | |
} | |
else { | |
// position argument | |
out[pars[i]] = arguments_[i]; | |
} | |
} | |
return out; | |
} | |
function test_me(arg1, arg2, arg3, arg4, arg5) { | |
var args = get_args(arguments); | |
console.log(args); | |
} | |
// emulate python's named argument call : test_me("who", "are", arg5="you") | |
test_me("who","are",{arg5:"you"}); | |
// prints {arg1:"who", arg2:"are", arg3:undefined, arg4:undefined, arg5:"you"} | |
test_me("who","are",{fag:"you"}); | |
// prints {arg1:"who", arg2:"are", arg3:{fag:"you"}, arg4:undefined, arg5:undefined} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment