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

220
Visualizações
How to write a function that only invokes a callback once, then returns the result of calling the function the first time, every subsequent calling

How to write a function that returns a callback, but only the result of the first time calling the callback.

Returns a function that is restricted to invoking func once. Repeat calls to the function return the value of the first call.

function once(func) {
 let result = func
 let counter = 0
 //let result 
 function inner (n) {
   counter++
   if (counter = 1) {
     return func
    }
   if (counter > 1) {
     return result
   }
 }
 return inner
}

I can't put my finger on what I'm doing wrong.

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

0

You're on the right track using the closure, you just have to

  1. Call func at least once (right now you just refer to it; more here)

  2. Remember the result of that for subsequent invocations

You don't need a counter, just some kind of flag; perhaps func itself, which you could clear:

function once(func) {
    let result;
    return () => {
        if (func) {
            result = func();
            func = null;
        }
        return result;
    };
}

function once(func) {
    let result;
    return () => {
        if (func) {
            result = func();
            func = null;
        }
        return result;
    };
}

const fn = () => {
    console.log("fn called");
    return 42;
};

console.log("Getting the function");
const f = once(fn);
console.log("Doing first call");
console.log(f());
// => fn called
// => 42
console.log("Doing second call");
console.log(f()); // 42
// => 42
console.log("Doing third call");
console.log(f()); // 42
// => 42

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