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

236
Visualizações
Number of times the callback needs to be called before executed

I got presented 4 interview questions and one of them is this:

Write a function after that takes the number of times the callback needs to be called before being executed as the first parameter and the callback as the second parameter.

function after(count, func) {
  // Implement the 'after' function
}

var called = function() { console.log("hello") };
var afterCalled = after(3, called);

afterCalled(); // -> nothing is printed
afterCalled(); // -> nothing is printed
afterCalled(); // -> 'hello' is printed

The way I solved the problem is this:

function after(count, cBack) {
  localStorage.setItem("aCount", count);
  return function () {
    let currCount = localStorage.getItem("aCount");

    if (currCount == 1) {
      cBack();
    } else {
      localStorage.setItem("aCount", --currCount);
    }
  };
}

let called = function () {
  console.log("hello");
};

let afterCalled = after(5, called);

afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();

I mean, the code works as intended but I have a feeling that localStorage is not the way. Am I missing somethig? Is there something in callback functions that I can use or I 'should' use to solve this problem? If so, what should I look up?

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

0

They probably expected you to use the closure formed by calling after (see comments):

let after = (count, callback) => {
    return () => {
        // Has our count reached one?
        if (count <= 1) {
            // Yes, call the callback
            callback();
        } else {
            // No, decrement the count
            --count;
        }
    };
};

let called = function () {
  console.log('hello')
};

let afterCalled = after(5, called);

afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();

The count parameter continues to exist as long as the function that after returns exists, because the function after returns is a closure over the context where it was created. So you can use that to remember the number of times called.

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