Here is the code that I got from this Named parameters in javascript:
var parameterfy = (function () {
var pattern = /function[^(]*\(([^)]*)\)/;
return function (func) {
// fails horribly for parameterless functions ;)
var args = func.toString().match(pattern)[1].split(/,\s*/);
return function () {
var named_params = arguments[arguments.length - 1];
if (typeof named_params === 'object') {
var params = [].slice.call(arguments, 0, -1);
if (params.length < args.length) {
for (var i = params.length, l = args.length; i < l; i++) {
params.push(named_params[args[i]]);
}
return func.apply(this, params);
}
}
return func.apply(null, arguments);
};
};
}());
var myObject = {
first: "",
second: "",
third: ""
};
var foo = parameterfy(function (a, b, c) {
//console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
myObject.first = a;
myObject.second = b;
myObject.third = c;
console.log("first " + myObject.first + " second " + myObject.second + " third " + myObject.third);
});
foo(1, 2, 3); // gives 1, 2, 3
foo({a: 11, c: 13}); // gives 11, undefined, 13
foo({ a: 11, b:myObject.second, c: 13 }); // in order to avoid undefined, this is
Note that, in second instance of foo
, I got undefined
as I didn't pass b
so I had to work around using third instance where I passed the current value of b.
Is there anyway to make it so that if I don't have to pass a value, for example, value of b
in this case so that it still updates the given values of a
and c
but retains the value of b
?
Something like the below may work:
var foo = parameterfy(function (a, b, c) {
//console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
if(typeof a != 'undefined'){myObject.first = a;}
if(typeof b != 'undefined'){myObject.second = b;}
if(typeof c != 'undefined'){myObject.third = c;}
console.log("first " + myObject.first + " second " + myObject.second + " third " + myObject.third);
});