Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
Javascript best & fast way for function overloading

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...

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda