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

205
Vistas
How to limit function calls in JS?

I need a function limitCalls (fn, maxCalls) that takes a function fn and returns a new function that can be called no more than the number of times specified in maxCalls. Test example:

 it('limitCalls', () => {
const makeIncrement = () => {
  let count = 0;

  return () => {
    count += 1;
    return count;
  };
};

const limitedIncrementA = limitCalls(makeIncrement(), 3);

expect(limitedIncrementA()).toBe(1);
expect(limitedIncrementA()).toBe(2);
expect(limitedIncrementA()).toBe(3);
expect(limitedIncrementA()).toBe(undefined);
expect(limitedIncrementA()).toBe(undefined);

const limitedIncrementB = limitCalls(makeIncrement(), 1);

expect(limitedIncrementB()).toBe(1);
expect(limitedIncrementB()).toBe(undefined);
expect(limitedIncrementB()).toBe(undefined);

});

I have:

var calls = 0;
export default function limitCalls(fn, maxCalls) {
  if (calls >= maxCalls) {
    return undefined;
  }
  calls += 1;
  return fn();
}

And error is limitedIncrementA is not a function. Help me please to realise it.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Instead of conditionally returning a function, always return a function that conditionally executes the fn callback:

function limitCalls(fn, maxCalls) {
  let count = 0;
  
  return function(...args) {
    return count++ < maxCalls ? fn(...args) : undefined;
  }
}

const limited = limitCalls(console.log, 3);

limited('one');
limited('two');
limited('three');
limited('four');

about 4 years ago · Juan Pablo Isaza Denunciar

0

In this snippet, limitedIncrementA isn't indeed a function. See this:

/* You're calling makeIncrement,
   so you're passing its return to 'limitCalls'
 */
const limitedIncrementA = limitCalls(makeIncrement(), 3);

/* Here, considering that makeIncrement exists,
   you're passing a reference to this functions,
   which can be called inside 'limitCalls'
 */
const limitedIncrementB = limitCalls(makeIncrement, 3);

So, supposing that makeIncrement returns 1, 2, 3, ..., your current code is equivalent to:

limitCalls(1, 3);
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