AniUI Academy

Allow only N calls

mediumFunctions & Closures+250 XPPractice

Sometimes the rule is not "once" but "three times": three hint reveals, five undo steps, two automatic retries. The counter belongs in the wrapper, not scattered through the caller.

Implement limitCalls(fn, max). It returns a wrapper that invokes fn for the first max calls, forwarding all arguments and preserving this, and returns fn's return value. From call max + 1 onwards fn is not invoked at all and the wrapper returns the value returned by the last successful invocation. When max is 0, fn is never invoked and the wrapper returns undefined. The wrapper also carries a remaining property: the number of invocations still allowed, which starts at max, drops by one per allowed call and never goes below 0.

Arguments

fnFunction
The function to cap.
maxnumber
Maximum number of times fn may run. 0 means never.

Returns

Function & { remaining: number } — A wrapper that runs fn up to max times, with a live remaining counter.

Examples

let calls = 0;
const run = limitCalls(() => { calls++; return calls; }, 2);

run(); // 1
run(); // 2
run(); // 2 — not invoked, returns last result
run.remaining; // 0
const never = limitCalls(() => "x", 0);
never();           // undefined — fn never ran
never.remaining;   // 0

What it has to do

  • Invoke fn for the first max calls only.
  • After the limit, return the last successful result without invoking fn.
  • With max of 0, never invoke fn and return undefined.
  • Keep a remaining property up to date, never dropping below 0.
  • Forward arguments and preserve this.

Notes

  • Keep both a used counter and the lastResult in the closure. Update wrapper.remaining after each call so a reader always sees the current value.
  • A max of 1 is once — this problem is the N-ary generalisation.
Asked atUberMeta

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.