Wrap a function to run at most N times, then return last result
A free plan lets a user run an expensive export three times per session. After that, the button keeps working, but it shows the last export instead of running a new one. When the user upgrades, the budget resets.
Implement limitCalls(fn, maxCalls). It returns a wrapped function that calls fn at most maxCalls times.
const limited = limitCalls(fn, maxCalls);
limited(...args); // => fn's result, or the last result once the budget is used up
limited.remaining(); // => number of calls left
limited.reset(); // restores the full budget and forgets the last result
limited calls fn with the same this and arguments, and returns its result.maxCalls calls were made, fn is not called again. limited returns the result of the most recent call to fn that returned normally, or undefined if none did.fn throws still uses up one call. The error propagates to the caller, and the remembered result does not change.fn runs, so if fn calls limited again, the inner call sees the reduced budget.remaining() returns how many calls to fn are left (never negative).reset() restores the budget to maxCalls and forgets the remembered result.maxCalls must be a non-negative integer. Otherwise, limitCalls throws a RangeError. With 0, fn is never called.let runs = 0;
const exportReport = limitCalls((format) => `report-${++runs}.${format}`, 2);
exportReport('csv'); // => 'report-1.csv'
exportReport('pdf'); // => 'report-2.pdf'
exportReport('csv'); // => 'report-2.pdf' (budget used up, fn not called)
exportReport.remaining(); // => 0
exportReport.reset();
exportReport('xlsx'); // => 'report-3.xlsx'