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