Call a function with positional or named params; called at top of funcName like arguments = namedParams.apply(func, arguments);
function test1(a, b, c) {
var r = namedParams.apply(test1, arguments);
a = r[0]; b = r[1]; c = r[2];
if (a !== 'a' || b !== 'b' || c !== 'c')
throw new Error ('incorrect params!');
}
test1('a', 'b', 'c');
test1({c: 'c', a: 'a', b: 'b'});
function namedParams() {
var functionArgsRegex = /^function\s*[^\(]*\(\s*([^\)]*)\)/m,
func = this,
funcArgsPart = func.toString().match(functionArgsRegex)[1],
args = funcArgsPart.split(',').map( function (arg) { return arg.trim() }),
vals = [],
arg0 = arguments.length === 1 && arguments[0];
if (arg0
&& typeof arg0 === "object"
&& typeof arg0 !== "function"
&& !Array.isArray(arg0)
&& Object.keys(arg0).length > 0) {
var paramsMap = arg0;
Object.keys(paramsMap)
.forEach (function(key) {
var index = args.indexOf(key);
if (~index) {
vals[index] = paramsMap[key];
}
});
}
else {
for (var i = 0, len = arguments.length; i < len; i++) {
vals.push(arguments[i]);
}
}
return vals;
}
if (module && module.exports) {
module.exports = namedParams;
}