Allow only N calls
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
fnmay run.0means 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; // 0const never = limitCalls(() => "x", 0);
never(); // undefined — fn never ran
never.remaining; // 0What it has to do
- Invoke
fnfor the firstmaxcalls only. - After the limit, return the last successful result without invoking
fn. - With
maxof0, never invokefnand returnundefined. - Keep a
remainingproperty up to date, never dropping below0. - Forward arguments and preserve
this.
Notes
- Keep both a
usedcounter and thelastResultin the closure. Updatewrapper.remainingafter each call so a reader always sees the current value. - A
maxof1isonce— this problem is the N-ary generalisation.
Stuck? The javascript course covers everything this challenge needs.
- 1.allows exactly max invocations
- 2.a max of one behaves like once
- 3.a max of zero never invokes the function
- 4.remaining counts down and stops at zero
- 5.forwards arguments and preserves this
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.