Skip to curriculum
Jump to the editor

6.5. Allow a function at most n calls

Easy
Topics

This question is in

6. Functions and closures
10–15 min

A free plan allows three exports. A tooltip explains a feature the first two times and then stays quiet. A retry button may try five times. Each is a function that is allowed to run only a fixed number of times, after which calling it changes nothing.

Write limitCalls(fn, n) in limit.js. It returns a new function. The first n calls of that function run fn and return its result. Every call after that returns the result of the last call that did run fn, without running it.

Signature

JAVASCRIPT
function limitCalls(fn, n) // returns a function
  • fn: the function to limit.
  • n: how many calls may run fn. A fraction is cut down toward zero (2.7 allows 2 calls). Zero, a negative number, NaN or a missing n allow none. Infinity allows every call.
  • The returned function returns fn's result, or the last result once the limit is reached (undefined if fn never ran).

Requirements

  1. limitCalls returns a function and does not call fn itself.
  2. Each of the first n calls runs fn with that call's arguments and this, and returns its result.
  3. Once n calls have run fn, later calls do not run it and return the last result, even when that result is falsy.
  4. n is cut to a whole number toward zero; 0, negative, NaN and missing mean fn never runs; Infinity means no limit.
  5. A call counts as soon as it starts: a call where fn throws uses up one of the n (and the error reaches the caller), and so does a call made from inside fn.
  6. Each limited function counts its own calls.

Examples

JAVASCRIPT
let exports = 0;
const exportFile = limitCalls(() => ++exports, 3);
exportFile(); // 1
exportFile(); // 2
exportFile(); // 3
exportFile(); // 3: fn did not run, the last result again
JAVASCRIPT
const greet = limitCalls((name) => "Hi " + name, 1);
greet("Ana"); // "Hi Ana"
greet("Bo");  // "Hi Ana"
JAVASCRIPT
const never = limitCalls(() => "ran", 0);
never(); // undefined

const twice = limitCalls(() => "ran", 2.9);
twice(); twice(); // "ran", "ran"
twice();          // "ran", but fn ran only twice

Environment

  • Plain JavaScript in a browser page; the tests call the global limitCalls from limit.js.
  • fn is always a function, and n is a number or missing (strings and other types are out of scope).
  • Out of scope: resetting the count, and time windows (rate limiting is a timer problem).

Hints

  1. Which built-in cuts 2.9 to 2 and -2.9 to -2, and what does it do with NaN?
  2. When should the count go up: before fn runs, or after it returns?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…