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

212
Visualizações
How to prevent a function call if the same arguments are passed?

I have the following code and I am trying to prevent the calculation inside of complexFunction in case same arguments are passed.

const complexFunction = (arg1, arg2) => { 
  /* complex calculation in here */ 
  console.log('complexFunction');
  return true;
};

// this is the method we need to implement
const memo=()=>{

}

const memoComplex = memo(complexFunction);

memoComplex(1, 2); // complex function should be executed   
memoComplex(1, 2); // complex function should not be invoked again, instead the cached result should be returned
memoComplex(1, 3); // complex function should be executed
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can simply use an array of objects which holds the arguments to check if they've been used before, the code below demonstrates the use

const usedArgs = [];
const memoComplex = (arg1, arg2) => {
    
    /* complex calculation in here */
    const value = arg1 + arg2;
    usedArgs.push({ arg1: arg1, arg2: arg2, data: value });
    return value;
};

const memo = (arg1, arg2) => {
    const exists = usedArgs.find(x => x.arg1 == arg1 && x.arg2 == arg2);
    if (exists) {
        console.log('loading from cache')
        return exists.data;
    } else return memoComplex(arg1, arg2);
}



console.log(memo(1, 2)); // complex function should be executed   
console.log(memo(1, 2)); // complex function should not be invoked again, instead the cached result should be returned
console.log(memo(1, 3)); // complex function should be executed

about 4 years ago · Juan Pablo Isaza Relatório

0

You could save the arguments passed and the result in Session Storage and on method call, look if you have already saved that in the storage, if that the case you could get it and return the result. Otherwise you would execute your method as always

sessionStorage.setItem('clé', 'valeur');
const complexFunction = (arg1, arg2) => { 
    // Get item return null if not found
    let potentialResult = sessionStorage.getItem("#1" + arg1.toString() + "#2" + arg2.toString());
    if(potentialResult !== null) {
        // If we have a result in session storage, that mean we have already done the calc
        // so we return the result
        return potentialResult;
    } else {
      // If we don't have a result, we just execute the function and save the result
      /* complex calculation in here */
      let result = "Your result"; // Assuming result is the result of your function
      // We save the result to avoid future calculation
      sessionStorage.setItem("#1" + arg1.toString() + "#2" + arg2.toString(), result);
      console.log('complexFunction');
      return true;
    }
};

But as said in the comments, this is more a hint than a solution, so please adapt it to your use case

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