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

267
Visualizações
Understanding higher order functions in JS: how does the following code guarantee that the code will only be called once?

I am trying to understand functional programming and saw the following example:

function onceOnly(f) {
    var hasRun = false;
    return function() {
        if(!hasRun){
            hasRun = true;
            return f();
        }
    }
}

// Call as many times as you like
var sendWelcomeEmail = onlyOnce(function() {
    emailServer.send(...);
});

There are a few things that I do not understand about this.

  • This technique should guarantee that emailServer.send(...) will be called only once. How does it do so? How does the state of hasRun get saved?
  • Is there any use to creating a function which returns f() inside onceOnly(f)? Why did we not simply do the following:
function onceOnly(f) {
    var hasRun = false;
    if(!hasRun){
        hasRun = true;
        return f();
    }
}

The source of this code can be found here

Thank you.

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

0

The aim of onlyOnce is to return a function, not calling a function. Your second example is calling the function and return the result of f.

Wherease, with the first implementation

//return a reference to an anonymous function
var sendWelcomeEmail = onlyOnce(...);
//you can use it to call after
sendWelcomeEmail();

Simply put a console.log() just before return f() you'll see the difference.

hasRun is first initiate with false. Once sendWelcomeEmail() is called, hasRun will be set to true. Since sendWelcomeEmail is referenced to an anonymous function, it is unique and exist in the memory, a second call to this same function will not trigger f() because hasRun is also uniquely referenced and got memorized.

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