Best use of the arguments property in JavaScript? - javascript

What's the right way to use the arguments property of a function?
This is how I'm currently using it, but I'm pretty sure I'm not using it correctly:
First, I define my parameters:
parameters = {};
parameters.ID = $tr.data('ID');
parameters.Name = 'Name goes here';
parameters.td = $td;
UpdateName(parameters);
And in the function:
var UpdateName = function(){
var local = {};
local.ID = arguments[0].ID;
local.Name = arguments[0].Name;
local.td = arguments[0].td;
local.jqXHR = $.ajax('Remote/Ajax.cfc', {
data: {
method:'UpdateName'
,returnformat:'json'
,ID:local.ID
,Name:local.Name
}
});
local.jqXHR.success(function(result){
if (result.MSG == '') {
local.td.text(local.Name).addClass('success');
} else {
local.td.addClass('err');
};
});
local.jqXHR.error(function(result){
local.td.addClass('err');
});
}

The arguments object is most useful for functions that accept an arbitrary/unknown number of arguments. The MDC gives this example for creating HTML lists of any length:
function list(type) {
var result = "<" + type + "l>";
// iterate through non-type arguments
for (var i = 1; i < arguments.length; i++)
result += "<li>" + arguments[i] + "</li>";
result += "</" + type + "l>"; // end list
return result;
}
...which can be used like this:
var listHTML = list("u", "One", "Two", "Three");
// listHTML is "<ul><li>One</li><li>Two</li><li>Three</li></ul>"
Because of arguments, we can pass any number of items to list and it just works. (Notice that even in this case the known parameter, type, is named and iteration of arguments begins on its second element.)
Your list of parameters is well-defined, so there's no reason not to simply name the parameters in your function declaration. Using arguments as you are is unnecessary and harder to read.

You technically are using it correctly, but I don't see the practical point in your code though. The arguments variable contains a array-like object of the arguments passed to a function. E.g.
function test() {
alert(arguments[0]);
alert(arguments[1]);
}
test("Hello", 123); // alerts Hello and 123
In your example, instead of an object, you can pass the properties as arguments and retrieve them from arguments.

JavaScript functions are capable of using named arguments.
In your case, this could simplify your code as follows:
var UpdateName = function(local) {
$.ajax('Remote/Ajax.cfc', {
data: {
method:'UpdateName',
returnformat:'json',
ID:local.ID,
Name:local.Name,
success: function(result) {
if (result.MSG == '') {
local.td.text(local.Name).addClass('success');
} else {
local.td.addClass('err');
}
},
error: function(result) {
local.td.addClass('err');
}
}
});
}
I modified the code so that you don't need to keep a reference to jqXHR anymore since you aren't doing anything with it anyway. I also moved the leading commas to the end of each line, but that is just a preference.

Related

JavaScript (NodeJS) equivalent for PHP's call_user_func_array()

Is there any equivalent function in JavaScript (NodeJS) similar to PHP's
call_user_func_array (http://php.net/manual/en/function.call-user-func-array.php). Which allows to call a function with array of parameters.
In my case, I have to call util.format with parameters that will be in an array.
Here is very simple example trying to show it.
var util = require("util");
function my_fundtion(items) {
var format_string = "";
for (var i=0; i < items.length; i++) {
format_string += " %s";
}
return util.format(format_string, /* here I want to pass items in items array */);
}
PHP has:
call_user_func_array('myfunc', array(1, 2, "foo", false));
While JS has:
myfunc.apply(null, [1, 2, "foo", false]);
The first null goes in the position of an object. You will make use of that if the function is intended to be a method. An example on using such invocation would be to slice array-like objects which are not arrays at all but seem like one (like the arguments object inside of a function):
Array.prototype.slice.apply(arguments, []);
Generally speaking, the syntax is:
(afunction).apply(obj|null, array of arguments)
You can try this:
function my_fundtion(items) {
var format_string = "";
for (var i=0; i < items.length; i++) {
format_string += " %s";
}
var new_items = items.slice();
new_items.unshift(format_string);
return util.format.apply(null, new_items);
}
IMHO that's the wrong approach for a function. Have you tried the following?
function my_fundtion(items) {
return items.join(" ");
}
Because call_user_func_array call function referenced by the function name which is in string. So, in JS we need to use eval.
Example:
const popup = (msg) => {
alert(msg);
}
const subject = {
popup(msg) {
alert(msg);
}
}
So,
eval("popup").apply(null, ['hi'])
eval("subject.popup").apply(null, ['hi'])
Correct me. If i wrong. ;)

How to create a "function that returns a function and splits csv file"? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 8 years ago.
I'm learning JS and I need help with the following task:
I need to create a function compile_csv_search(text, key_name) that parses text in
the CSV format. (not required to handle quoting and escaping in values;
assume field values never contain commas or other special characters.)
A function must return a function that looks up a record by a value of the
field specified as the second argument to compile_csv_search. Assume that all
values in the key field are unique.
Sample usage:
var csv_by_name = compile_csv_search(
"ip,name,desc\n"+
"1.94.0.2,server1,Main Server\n"+
"1.53.8.1,server2,Backup Server\n",
"name");
console.log(csv_by_name("server2"));
console.log(csv_by_name("server9"));
...will print:
{ip: "10.52.5.1", name: "server2", desc: "Backup Server"}
undefined
** I didn't understand what does it mean "function that return function". How can function return another function?
Thank you!
P.S.
attaching my solution for your review
function compile_csv_search(csvServerData){
var header = csvServerData.split('\n')[0].split(",");
var spleatedServerData = csvServerData.split('\n');
return function(serverName)
{
for(var i = 1; i < spleatedServerData.length; i++){
var singleServer = spleatedServerData[i].split(',')
var result = {};
var exist = false;
for (var j = 0; j < header.length; j++) {
if(singleServer.indexOf(serverName) == -1)
break;
exist = true;
result[header[j]] = singleServer[j];
}
if(exist){
return(result);
break;
}
}
}
}
var csv_by_name = compile_csv_search(
"ip,name,desc\n"+
"10.49.1.4,server1,Main Server\n"+
"10.52.5.1,server2,Backup Server\n");
Functions in JavaScript are objects; they can be referred to by variables, passed as arguments and returned from functions like any other object.
Here's a function that returns an object:
function returnObject() {
var result = { a: 1, b: 2, c: 3 };
return result;
}
And here's a function that returns another function:
function returnFunction() {
var result = function() {
console.log('another function!');
}
return result;
}
Notice how they're really similar - object returned by the first function is a plain Object created using object literal syntax ({}), and the object returned by the second happens to be a function.
You could call the inner, returned function like this:
var out = returnFunction();
out();
Or even returnFunction()();
However, you can't just call result() - result is only defined inside of returnFunction. The only way to access it from outside is to retrieve it by calling the outer function.
Something like this would be fine:
function compile_csv_search(text, key_name) {
var lines = text.split('\n');
var keys = lines[0].split(',');
var key_index = keys.indexOf(key_name);
return function(value) {
for(var i = 1; i<lines.length; i++) {
current_line_values = lines[i].split(',');
if(current_line_values[key_index] === value) {
var result = {};
for(var j = 0; j<keys.length; j++) {
result[keys[j]] = current_line_values[j];
}
return result;
}
}
}
}
Also see this fiddle: http://jsfiddle.net/efha0drq/
You can always treat a function the same as any other js objects. Assign to a variable, pass to a function, store in an array... all are fine.
The magic in this example is that, you can read/write the variables defined in the compile_csv_search() function within the returned function. So it's possible to store something in the local variables of the defining function, and later retrieve from the returned one, even when the defining function has finished execution long time ago. You may have heard of "closure", right?

How do I check if a property exists in an object/dictionary?

I'm iterating over an array of words and trying to stuff them in an object literal so I can assign the value of how many times those words occur to each word in the literal/dictionary. The problem is I need to check to make sure that word hasn't already been added into my literal. I tried using in to check if the property exists in the literal but it's throwing an error:
Cannot use 'in' operator to search for 'We' in undefined
Here's problematic function:
I commented the line that's causing the problem
function wordCountDict(filename) {
wordCount = {};
inputFile = fs.readFile( root + filename, 'utf8', function( error, data ) {
if(error) {
console.log('error: ', error)
return false;
}
var words = data.split(" ");
for (i in words) {
if(words[i] in wordCount) { // This is where the problem occurs
wordCount[words[i]]++;
} else {
wordCount[words[i]] = 1;
}
console.log(words[i]);
}
});
}
I'm coming from python and this was always the best/easiest way to achieve this, but javascript doesn't seem to agree.
How would I do this in JavaScript?
Declare wordCount as a local variable to that function. It is probably getting overwritten elsewhere:
function wordCountDict(filename) {
var wordCount = {};
...
}
This is a bad idea
for (i in words) {
do not use a for loop to loop through an array! If something is added to the array prototype it will be checked.
var words = data.split(" ");
for (var i=0; i<words.length; i++) {
if(words[i] in wordCount) {
Next thing, is readFile is asynchronous. If code outide of it resets wordCount to an undefined value, you can get this error. You are better off using a local variable and setting the global value when the looping is done. Also that return false does NOTHING inside the readFile.
function wordCountDict(filename) {
var tempWordCount = {};
var inputFile = fs.readFile( root + filename, 'utf8', function( error, data ) {
if(error) {
console.log('error: ', error)
return false;
}
var words = data.split(" ");
for (var i = 0; i<words.length; i++) {
if(words[i] in wordCount) { // This is where the problem occurs
wordCount[words[i]]++;
} else {
wordCount[words[i]] = 1;
}
console.log(words[i]);
}
wordCount = tempWordCount; //set the global variable equal to the local value
});
}
If all you would like to do is check for existance in the object, you can use this:
if(typeof wordCount[words[i]] === 'undefined'){
...
}
I would not recommend just using if(wordCount[words[i]]) because technically there could be a property of the object that exists but evaluates to false.
Note that in Javascript doing something like myObject.something is equivalent to myObject['something'] on an object, and that when you use myObject['somethingElse'] you are basically just dynamically adding members to the object. In Javascript, objects can be used like Python dictionaries, but they really aren't the same thing.

How to overload functions in javascript?

Classical (non-js) approach to overloading:
function myFunc(){
//code
}
function myFunc(overloaded){
//other code
}
Javascript wont let more than one function be defined with the same name. As such, things like this show up:
function myFunc(options){
if(options["overloaded"]){
//code
}
}
Is there a better workaround for function overloading in javascript other than passing an object with the overloads in it?
Passing in overloads can quickly cause a function to become too verbose because each possible overload would then need a conditional statement. Using functions to accomplish the //code inside of those conditional statements can cause tricky situations with scopes.
There are multiple aspects to argument overloading in Javascript:
Variable arguments - You can pass different sets of arguments (in both type and quantity) and the function will behave in a way that matches the arguments passed to it.
Default arguments - You can define a default value for an argument if it is not passed.
Named arguments - Argument order becomes irrelevant and you just name which arguments you want to pass to the function.
Below is a section on each of these categories of argument handling.
Variable Arguments
Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of myFunc() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.
jQuery does this all the time. You can make some of the arguments optional or you can branch in your function depending upon what arguments are passed to it.
In implementing these types of overloads, you have several different techniques you can use:
You can check for the presence of any given argument by checking to see if the declared argument name value is undefined.
You can check the total quantity or arguments with arguments.length.
You can check the type of any given argument.
For variable numbers of arguments, you can use the arguments pseudo-array to access any given argument with arguments[i].
Here are some examples:
Let's look at jQuery's obj.data() method. It supports four different forms of usage:
obj.data("key");
obj.data("key", value);
obj.data();
obj.data(object);
Each one triggers a different behavior and, without using this dynamic form of overloading, would require four separate functions.
Here's how one can discern between all these options in English and then I'll combine them all in code:
// get the data element associated with a particular key value
obj.data("key");
If the first argument passed to .data() is a string and the second argument is undefined, then the caller must be using this form.
// set the value associated with a particular key
obj.data("key", value);
If the second argument is not undefined, then set the value of a particular key.
// get all keys/values
obj.data();
If no arguments are passed, then return all keys/values in a returned object.
// set all keys/values from the passed in object
obj.data(object);
If the type of the first argument is a plain object, then set all keys/values from that object.
Here's how you could combine all of those in one set of javascript logic:
// method declaration for .data()
data: function(key, value) {
if (arguments.length === 0) {
// .data()
// no args passed, return all keys/values in an object
} else if (typeof key === "string") {
// first arg is a string, look at type of second arg
if (typeof value !== "undefined") {
// .data("key", value)
// set the value for a particular key
} else {
// .data("key")
// retrieve a value for a key
}
} else if (typeof key === "object") {
// .data(object)
// set all key/value pairs from this object
} else {
// unsupported arguments passed
}
},
The key to this technique is to make sure that all forms of arguments you want to accept are uniquely identifiable and there is never any confusion about which form the caller is using. This generally requires ordering the arguments appropriately and making sure that there is enough uniqueness in the type and position of the arguments that you can always tell which form is being used.
For example, if you have a function that takes three string arguments:
obj.query("firstArg", "secondArg", "thirdArg");
You can easily make the third argument optional and you can easily detect that condition, but you cannot make only the second argument optional because you can't tell which of these the caller means to be passing because there is no way to identify if the second argument is meant to be the second argument or the second argument was omitted so what's in the second argument's spot is actually the third argument:
obj.query("firstArg", "secondArg");
obj.query("firstArg", "thirdArg");
Since all three arguments are the same type, you can't tell the difference between different arguments so you don't know what the caller intended. With this calling style, only the third argument can be optional. If you wanted to omit the second argument, it would have to be passed as null (or some other detectable value) instead and your code would detect that:
obj.query("firstArg", null, "thirdArg");
Here's a jQuery example of optional arguments. both arguments are optional and take on default values if not passed:
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
Here's a jQuery example where the argument can be missing or any one of three different types which gives you four different overloads:
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
Named Arguments
Other languages (like Python) allow one to pass named arguments as a means of passing only some arguments and making the arguments independent of the order they are passed in. Javascript does not directly support the feature of named arguments. A design pattern that is commonly used in its place is to pass a map of properties/values. This can be done by passing an object with properties and values or in ES6 and above, you could actually pass a Map object itself.
Here's a simple ES5 example:
jQuery's $.ajax() accepts a form of usage where you just pass it a single parameter which is a regular Javascript object with properties and values. Which properties you pass it determine which arguments/options are being passed to the ajax call. Some may be required, many are optional. Since they are properties on an object, there is no specific order. In fact, there are more than 30 different properties that can be passed on that object, only one (the url) is required.
Here's an example:
$.ajax({url: "http://www.example.com/somepath", data: myArgs, dataType: "json"}).then(function(result) {
// process result here
});
Inside of the $.ajax() implementation, it can then just interrogate which properties were passed on the incoming object and use those as named arguments. This can be done either with for (prop in obj) or by getting all the properties into an array with Object.keys(obj) and then iterating that array.
This technique is used very commonly in Javascript when there are large numbers of arguments and/or many arguments are optional. Note: this puts an onus on the implementating function to make sure that a minimal valid set of arguments is present and to give the caller some debug feedback what is missing if insufficient arguments are passed (probably by throwing an exception with a helpful error message).
In an ES6 environment, it is possible to use destructuring to create default properties/values for the above passed object. This is discussed in more detail in this reference article.
Here's one example from that article:
function selectEntries({ start=0, end=-1, step=1 } = {}) {
···
};
Then, you can call this like any of these:
selectEntries({start: 5});
selectEntries({start: 5, end: 10});
selectEntries({start: 5, end: 10, step: 2});
selectEntries({step: 3});
selectEntries();
The arguments you do not list in the function call will pick up their default values from the function declaration.
This creates default properties and values for the start, end and step properties on an object passed to the selectEntries() function.
Default values for function arguments
In ES6, Javascript adds built-in language support for default values for arguments.
For example:
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
Further description of the ways this can be used here on MDN.
Overloading a function in JavaScript can be done in many ways. All of them involve a single master function that either performs all the processes, or delegates to sub-functions/processes.
One of the most common simple techniques involves a simple switch:
function foo(a, b) {
switch (arguments.length) {
case 0:
//do basic code
break;
case 1:
//do code with `a`
break;
case 2:
default:
//do code with `a` & `b`
break;
}
}
A more elegant technique would be to use an array (or object if you're not making overloads for every argument count):
fooArr = [
function () {
},
function (a) {
},
function (a,b) {
}
];
function foo(a, b) {
return fooArr[arguments.length](a, b);
}
That previous example isn't very elegant, anyone could modify fooArr, and it would fail if someone passes in more than 2 arguments to foo, so a better form would be to use a module pattern and a few checks:
var foo = (function () {
var fns;
fns = [
function () {
},
function (a) {
},
function (a, b) {
}
];
function foo(a, b) {
var fnIndex;
fnIndex = arguments.length;
if (fnIndex > foo.length) {
fnIndex = foo.length;
}
return fns[fnIndex].call(this, a, b);
}
return foo;
}());
Of course your overloads might want to use a dynamic number of parameters, so you could use an object for the fns collection.
var foo = (function () {
var fns;
fns = {};
fns[0] = function () {
};
fns[1] = function (a) {
};
fns[2] = function (a, b) {
};
fns.params = function (a, b /*, params */) {
};
function foo(a, b) {
var fnIndex;
fnIndex = arguments.length;
if (fnIndex > foo.length) {
fnIndex = 'params';
}
return fns[fnIndex].apply(this, Array.prototype.slice.call(arguments));
}
return foo;
}());
My personal preference tends to be the switch, although it does bulk up the master function. A common example of where I'd use this technique would be a accessor/mutator method:
function Foo() {} //constructor
Foo.prototype = {
bar: function (val) {
switch (arguments.length) {
case 0:
return this._bar;
case 1:
this._bar = val;
return this;
}
}
}
You cannot do method overloading in strict sense. Not like the way it is supported in java or c#.
The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.
One of the way I think is suitable for most of the case is follows -
Lets say you have method
function foo(x)
{
}
Instead of overloading method which is not possible in javascript you can define a new method
fooNew(x,y,z)
{
}
and then modify the 1st function as follows -
function foo(x)
{
if(arguments.length==2)
{
return fooNew(arguments[0], arguments[1]);
}
}
If you have many such overloaded method consider using switch than just if-else statements.
(more details)
PS: Above link goes to my personal blog that has additional details on this.
I am using a bit different overloading approach based on arguments number.
However i believe John Fawcett's approach is also good.
Here the example, code based on John Resig's (jQuery's Author) explanations.
// o = existing object, n = function name, f = function.
function overload(o, n, f){
var old = o[n];
o[n] = function(){
if(f.length == arguments.length){
return f.apply(this, arguments);
}
else if(typeof o == 'function'){
return old.apply(this, arguments);
}
};
}
usability:
var obj = {};
overload(obj, 'function_name', function(){ /* what we will do if no args passed? */});
overload(obj, 'function_name', function(first){ /* what we will do if 1 arg passed? */});
overload(obj, 'function_name', function(first, second){ /* what we will do if 2 args passed? */});
overload(obj, 'function_name', function(first,second,third){ /* what we will do if 3 args passed? */});
//... etc :)
I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:
var out = def({
'int': function(a) {
alert('Here is int '+a);
},
'float': function(a) {
alert('Here is float '+a);
},
'string': function(a) {
alert('Here is string '+a);
},
'int,string': function(a, b) {
alert('Here is an int '+a+' and a string '+b);
},
'default': function(obj) {
alert('Here is some other value '+ obj);
}
});
out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);
The methods used to achieve this:
var def = function(functions, parent) {
return function() {
var types = [];
var args = [];
eachArg(arguments, function(i, elem) {
args.push(elem);
types.push(whatis(elem));
});
if(functions.hasOwnProperty(types.join())) {
return functions[types.join()].apply(parent, args);
} else {
if (typeof functions === 'function')
return functions.apply(parent, args);
if (functions.hasOwnProperty('default'))
return functions['default'].apply(parent, args);
}
};
};
var eachArg = function(args, fn) {
var i = 0;
while (args.hasOwnProperty(i)) {
if(fn !== undefined)
fn(i, args[i]);
i++;
}
return i-1;
};
var whatis = function(val) {
if(val === undefined)
return 'undefined';
if(val === null)
return 'null';
var type = typeof val;
if(type === 'object') {
if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
return 'array';
if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
return 'date';
if(val.hasOwnProperty('toExponential'))
type = 'number';
if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
return 'string';
}
if(type === 'number') {
if(val.toString().indexOf('.') > 0)
return 'float';
else
return 'int';
}
return type;
};
In javascript you can implement the function just once and invoke the function without the parameters myFunc() You then check to see if options is 'undefined'
function myFunc(options){
if(typeof options != 'undefined'){
//code
}
}
https://github.com/jrf0110/leFunc
var getItems = leFunc({
"string": function(id){
// Do something
},
"string,object": function(id, options){
// Do something else
},
"string,object,function": function(id, options, callback){
// Do something different
callback();
},
"object,string,function": function(options, message, callback){
// Do something ca-raaaaazzzy
callback();
}
});
getItems("123abc"); // Calls the first function - "string"
getItems("123abc", {poop: true}); // Calls the second function - "string,object"
getItems("123abc", {butt: true}, function(){}); // Calls the third function - "string,object,function"
getItems({butt: true}, "What what?" function(){}); // Calls the fourth function - "object,string,function"
No Problem with Overloading in JS , The pb how to maintain a clean code when overloading function ?
You can use a forward to have clean code, based on two things:
Number of arguments (when calling the function).
Type of arguments (when calling the function)
function myFunc(){
return window['myFunc_'+arguments.length+Array.from(arguments).map((arg)=>typeof arg).join('_')](...arguments);
}
/** one argument & this argument is string */
function myFunc_1_string(){
}
//------------
/** one argument & this argument is object */
function myFunc_1_object(){
}
//----------
/** two arguments & those arguments are both string */
function myFunc_2_string_string(){
}
//--------
/** Three arguments & those arguments are : id(number),name(string), callback(function) */
function myFunc_3_number_string_function(){
let args=arguments;
new Person(args[0],args[1]).onReady(args[3]);
}
//--- And so on ....
How about using a proxy (ES6 Feature)?
I didn't find anywhere mentioning this method of doing it. It might be impractical but it's an interesting way nonetheless.
It's similar to Lua's metatables, where you can "overload" the call operator with the __call metamethod in order to achieve overloading.
In JS, it can be done with the apply method in a Proxy handler. You can check the arguments' existence, types, etc. inside the said method, without having to do it in the actual function.
MDN: proxy apply method
function overloads() {}
overloads.overload1 = (a, b) => {
return a + b;
}
overloads.overload2 = (a, b, c) => {
return a + b + c;
}
const overloadedFn = new Proxy(overloads, { // the first arg needs to be an Call-able object
apply(target, thisArg, args) {
if (args[2]) {
return target.overload2(...args);
}
return target.overload1(...args);
}
})
console.log(overloadedFn(1, 2, 3)); // 6
console.log(overloadedFn(1, 2)); // 3
Check this out:
http://www.codeproject.com/Articles/688869/Overloading-JavaScript-Functions
Basically in your class, you number your functions that you want to be overloaded and then with one function call you add function overloading, fast and easy.
Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.
function optionsObjectTest(x, y, opts) {
opts = opts || {}; // default to an empty options object
var stringValue = opts.stringValue || "string default value";
var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;
return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";
}
here is an example on how to use options object
For this you need to create a function that adds the function to an object, then it will execute depending on the amount of arguments you send to the function:
<script >
//Main function to add the methods
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function(){
if (fn.length == arguments.length)
return fn.apply(this, arguments)
else if (typeof old == 'function')
return old.apply(this, arguments);
};
}
 var ninjas = {
values: ["Dean Edwards", "Sam Stephenson", "Alex Russell"]
};
//Here we declare the first function with no arguments passed
addMethod(ninjas, "find", function(){
return this.values;
});
//Second function with one argument
addMethod(ninjas, "find", function(name){
var ret = [];
for (var i = 0; i < this.values.length; i++)
if (this.values[i].indexOf(name) == 0)
ret.push(this.values[i]);
return ret;
});
//Third function with two arguments
addMethod(ninjas, "find", function(first, last){
var ret = [];
for (var i = 0; i < this.values.length; i++)
if (this.values[i] == (first + " " + last))
ret.push(this.values[i]);
return ret;
});
//Now you can do:
ninjas.find();
ninjas.find("Sam");
ninjas.find("Dean", "Edwards")
</script>
How about using spread operator as a parameter? The same block can be called with Multiple parameters. All the parameters are added into an array and inside the method you can loop in based on the length.
function mName(...opt){
console.log(opt);
}
mName(1,2,3,4); //[1,2,3,4]
mName(1,2,3); //[1,2,3]
I like to add sub functions within a parent function to achieve the ability to differentiate between argument groups for the same functionality.
var doSomething = function() {
var foo;
var bar;
};
doSomething.withArgSet1 = function(arg0, arg1) {
var obj = new doSomething();
// do something the first way
return obj;
};
doSomething.withArgSet2 = function(arg2, arg3) {
var obj = new doSomething();
// do something the second way
return obj;
};
What you are trying to achieve is best done using the function's local arguments variable.
function foo() {
if (arguments.length === 0) {
//do something
}
if (arguments.length === 1) {
//do something else
}
}
foo(); //do something
foo('one'); //do something else
You can find a better explanation of how this works here.
(() => {
//array that store functions
var Funcs = []
/**
* #param {function} f overload function
* #param {string} fname overload function name
* #param {parameters} vtypes function parameters type descriptor (number,string,object....etc
*/
overloadFunction = function(f, fname, ...vtypes) {
var k,l, n = false;
if (!Funcs.hasOwnProperty(fname)) Funcs[fname] = [];
Funcs[fname].push([f, vtypes?vtypes: 0 ]);
window[fname] = function() {
for (k = 0; k < Funcs[fname].length; k++)
if (arguments.length == Funcs[fname][k][0].length) {
n=true;
if (Funcs[fname][k][1]!=0)
for(i=0;i<arguments.length;i++)
{
if(typeof arguments[i]!=Funcs[fname][k][1][i])
{
n=false;
}
}
if(n) return Funcs[fname][k][0].apply(this, arguments);
}
}
}
})();
//First sum function definition with parameter type descriptors
overloadFunction(function(a,b){return a+b},"sum","number","number")
//Second sum function definition with parameter with parameter type descriptors
overloadFunction(function(a,b){return a+" "+b},"sum","string","string")
//Third sum function definition (not need parameter type descriptors,because no other functions with the same number of parameters
overloadFunction(function(a,b,c){return a+b+c},"sum")
//call first function
console.log(sum(4,2));//return 6
//call second function
console.log(sum("4","2"));//return "4 2"
//call third function
console.log(sum(3,2,5));//return 10
//ETC...

Javascript, passing a function in an object literal and is it callable?

always in the process of learning Javascript and modifying a cool autocomplete library, i am now in front of this :
i need to check if something passed in an object literal is a variable/field (that is to be considered as a simple value) or is something that can be called.
(as MY autocomplete depend on many input fields, i need to "value" the right things, just before the Ajax.Request) so that this declaration (see the 'extra' parts...)
myAutoComplete = new Autocomplete('query', {
serviceUrl:'autoComplete.rails',
minChars:3,
maxHeight:400,
width:300,
deferRequestBy:100,
// callback function:
onSelect: function(value, data){
alert('You selected: ' + value + ', ' + data);
}
// the lines below are the extra part that i add to the library
// an optional parameter, that will handle others arguments to pass
// if needed, these must be value-ed just before the Ajax Request...
, extraParametersForAjaxRequest : {
myExtraID : function() { return document.getElementById('myExtraID').value; }
}
see the "1 // here i'm lost..." below, and instead of 1 => i would like to check, if extraParametersForAjaxRequest[x] is callable or not, and call it if so, keeping only its value if not. So that, i get the right value of my other inputs... while keeping a really generic approach and clean modification of this library...
{
var ajaxOptions = {
parameters: { query: this.currentValue , },
onComplete: this.processResponse.bind(this),
method: 'get'
};
if (this.options.hasOwnProperty('extraParametersForAjaxRequest'))
{
for (var x in this.options.extraParametersForAjaxRequest)
{
ajaxOptions.parameters[x] = 1 // here i'm lost...
}
}
new Ajax.Request(this.serviceUrl, ajaxOptions );
You can do a typeof to see if the parameter is a function, and call it if it is.
var value;
for (var x in this.options.extraParametersForAjaxRequest)
{
value = this.options.extraParametersForAjaxRequest[x];
if (typeof(value) == 'function') {
ajaxOptions.parameters[x] = value();
}
else {
ajaxOptions.parameters[x] = value;
}
}
if (typeof this.options.extraParametersForAjaxRequest[x]==='function') {
}
You should also do this:
if (this.options.extraParametersForAjaxRequest.hasOwnProperty(x) {
if (typeof this.options.extraParametersForAjaxRequest[x]==='function') {
}
}
when iterating through properties of objects, otherwise you can end up looking at prototype members too.
Another suggestion is to make this more readable with an alias for the thing you're working with. So the ultimate would be:
var opts = this.options.extraParametersForAjaxRequest;
// don't need to check for existence of property explicitly with hasOwnProperty
// just try to access it, and check to see if the result is
// truthy. if extraParametersForAjaxRequest isn't there, no error will
// result and "opts" will just be undefined
if (opts)
{
for (var x in opts) {
if (opts.hasOwnProperty(x) && typeof opts[x]==='function') {
}
}
}

Categories

Resources