Cache Results With a Memoize Wrapper

Last lesson, once() kept a single result in its closure and handed it back on every later call. Marco’s big screen needs something related. It shows every team’s best round so far and asks for those answers again every time it redraws.

In this lesson, you’ll write memoize(), a wrapper that keeps a cache in a closure, with one result per set of arguments, so a function doesn’t repeat its work for the same arguments. Start by counting how much work the screen repeats.

Spot the Repeated Work

Each time the screen needs a team’s best round, a lookup finds the team and compares its rounds so far. Here it is for three of the five teams, with a lookups counter:

Language: JavaScript Filename: best_round.js
const teams = [
  { name: "The Lamplighters", rounds: [8, 6, 9, 7, 10] },
  { name: "Know-It-Owls", rounds: [7, 9, 0, 8, 6] },
  { name: "Table Six", rounds: [6, 8, 7, 5, 9] },
];
let lookups = 0;

function bestRound(teamName, roundsPlayed) {
  lookups += 1;
  const team = teams.find(
    (entry) => entry.name === teamName
  );
  const played = team.rounds.slice(0, roundsPlayed);
  return Math.max(...played);
}

console.log(bestRound("Table Six", 3));
console.log(bestRound("Table Six", 3));
console.log(bestRound("Know-It-Owls", 3));
console.log(bestRound("Table Six", 3));
console.log(`Lookups: ${lookups}`);

The .slice(0, roundsPlayed) call keeps the rounds played so far, and Math.max(...played) spreads them out as separate arguments to find the largest. Run the file, and count the lookups:

Language: Shell
$ node best_round.js
8
8
9
8
Lookups: 4

Table Six’s best round after three rounds is 8 every time, yet the function did the work three times to say so. This lookup is a toy, but slow work, such as a calculation over a season of quiz nights, repeats the same way.

The fix is to remember each answer the first time you work it out. Storing a function’s results by their arguments and returning a stored result when the same arguments come back is called memoization. The stored results are a cache. A closure can keep a cache alive and private between calls, as once() kept its called flag.

Keep Results in a Map

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.