Memoization in JavaScript

Level 4242 keystrokes

Memoization caches function results to avoid repeated expensive calculations.

JavaScript code

// Memoize wrapper function
1function memoize(fn) {
// Cache object to store results
2 const cache = {};
// Return memoized function
3 return (arg) => {
// If arg is not cached yet, compute fn(arg) and store it
4 if (!(arg in cache)) cache[arg] = fn(arg);
// Return cached result
5 return cache[arg];
6 };
7}
// Create memoized square function that logs when calculating
8const square = memoize(n => { console.log("calc"); return n * n; });
// First call: calculates and caches
9console.log(square(4));
// Second call: returns cached result (no "calc" logged)
10console.log(square(4));

Output

calc
16
16
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 11
  • )× 11
  • ;× 9
  • =× 5
  • {× 4
  • }× 4
  • .× 3
  • "× 2
  • [× 2
  • ]× 2

More JavaScript examples at level 4

← JavaScript typing practice