1

I wrote the following code for overloading functions in Javascript. This code can run slowly on large projects. Are there other ways to implement overloading functions in Javascript? Any other faster and more practical way?

(() => {
  //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((a,b)=>{return a+b},"sum","number","number")
//Second sum function definition with parameter with parameter type descriptors
overloadFunction((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((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...
Cem Frt
  • 31
  • 4
  • 1
    What is this code supposed to do? And please don't just say "overloads functions" - that's already part of the question. I don't understand *how*. And I don't feel like trying to reverse engineer the solution from the code. Therefore, I cannot guess what the actual goal is. Nor can I offer an alternative to reach that goal. – VLAZ Nov 17 '21 at 07:17
  • 1
    Does this answer your question? [Function overloading in Javascript - Best practices](https://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices) – juzraai Nov 17 '21 at 07:18
  • 1
    The basic answer to the question is: Don't. Just write the function, in the usual way, perhaps with default parameter values; or write multiple functions with different names. If you really need to, accept a rest param and work out what to do from the length of that param. There are some issues above: You're not declaring variables, so you're creating globals implicitly (example: `createFunc`), all the functions you create are also globals which is poor practice (the global namespace is already far too crowded), `new Array()` is better written `[]`, ... – T.J. Crowder Nov 17 '21 at 07:21
  • I add functions with same name but different context to Funcs variable. Funcs have own scope and sperated from global namespace and global scobe. There is only one global function for call other same name fuctions from funcs. (window[fname] = function() {...). – Cem Frt Nov 17 '21 at 08:11

1 Answers1

1

The concept overload is to avoid a function with infinite parameters. That is the opposite of your pattern. A function should ideally have a handful of parameters. An overloaded function passes varied parameters within the overloaded parameter.

function overload(fname, arr=[]){
 let sum = 0;
 for(let i=0; i<arr.length; i++){
  sum += arr[i];
 }
 return fname + sum;
}

overload("Juan", [1]);

As such, arr isn't considered overloaded, it's of indeterminate length. But if instead of arr, you had obj, you could pass any number of types or values indiscriminately.

function overload(fname, obj={}){
 if(obj.arr){}
 if(obj.f){}
}

overload("Juan", {"arr":[1], "f":true, "infinite":-Infinity});

This overloaded parameter would be ideal for data with questionable scope or origin.

PartialFlavor_55KP
  • 137
  • 1
  • 3
  • 13