Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda