Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
¿Cómo limitar las llamadas a funciones en JS?

Necesito una función limitCalls (fn, maxCalls) que tome una función fn y devuelva una nueva función a la que no se pueda llamar más que la cantidad de veces especificada en maxCalls. Ejemplo de prueba:

 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);

});

Tengo:

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

Y el error es limitedIncrementA no es una función. Ayúdame por favor a darme cuenta.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

En lugar de devolver condicionalmente una función, siempre devuelva una función que ejecute condicionalmente la devolución de llamada fn :

 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 Report

0

En este fragmento, limitedIncrementA no es realmente una función. Mira esto:

 /* 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);

Entonces, suponiendo que makeIncrement devuelve 1, 2, 3, ..., su código actual es equivalente a:

 limitCalls(1, 3);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!