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

186
Visualizações
How to excute a function only once for same argument

My function call is given below:

await insertingMatchIdsInAllTeamPlayers(fieldersA, matchID)

Suppose the function is called with matchID '1', it should get executed, but if the function is called again with matchId '1'(It will in my case), it should not be executed. However, if it is called with id '2' (basically id !== '1'), it should be executed. I don't care for fieldersA argument.

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

0

You could track all passed arguments in array outside of the function. When you call the function, it will check, if the supplied argument is in the array. If it's not, call the function and insert the argument into the array. If the argument is already in the array, don't call the function.

const suppliedMatchIDs = [];

function insertingMatchIdsInAllTeamPlayers(fieldersA, matchID) {
    if (suppliedMatchIDs.includes(matchID)) {
      return;
    } else {
      suppliedMatchIDs.push(matchID);
    }

    // Your function here
}

The general concept of caching arguments to speed up function calls is called memoization.

about 4 years ago · Juan Pablo Isaza Relatório

0

const matchIdFirstTimeOne = true
if(matchId === 1 && matchIdFirstTimeOne) {
  await insertingMatchIdsInAllTeamPlayers(fieldersA, matchID);
  matchIFirstTimeOne = false
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Using closure could solve it.

var insertingMatchIdsInAllTeamPlayers = (function() {
    var executed = [];
    return function(fieldersA,val) {
        if (executed.indexOf(val) == -1) {
            executed.push(val);
            console.log(val);
        }
    };
})();

insertingMatchIdsInAllTeamPlayers('',1); // console.log(1)
insertingMatchIdsInAllTeamPlayers('',1); // 
insertingMatchIdsInAllTeamPlayers('',2); // console.log(2)
insertingMatchIdsInAllTeamPlayers('',2); // 
insertingMatchIdsInAllTeamPlayers('',3); // console.log(3)
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