Memoization Pattern in JavaScript

Level 5409 keystrokes

Memoization caches function results based on arguments to avoid redundant computations.

JavaScript code

// Define memoization higher-order function
1function memoize(fn) {
// Create cache using Map
2 const cache = new Map();
// Return memoized function
3 return function(...args) {
// Create cache key from arguments
4 const key = JSON.stringify(args);
// Check if result is cached
5 if (cache.has(key)) {
// Log cache hit
6 console.log("Cache hit");
// Return cached result
7 return cache.get(key);
8 }
// Log that we're computing
9 console.log("Computing");
// Call original function
10 const result = fn.apply(this, args);
// Store result in cache
11 cache.set(key, result);
// Return computed result
12 return result;
13 };
14}
// Create a memoized factorial
// The recursive call also goes through the memoized version, so 5..1 are each cached
15const factorial = memoize(n => n <= 1 ? 1 : n * factorial(n - 1));
// First call: prints "Computing" 5 times (n = 5..1), then 120
16console.log(factorial(5));
// Second call: "Cache hit", then 120 without recomputing
17console.log(factorial(5));

Output

Computing
Computing
Computing
Computing
Computing
120
Cache hit
120
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.

  • (× 17
  • )× 17
  • ;× 12
  • .× 12
  • =× 6
  • "× 4
  • {× 3
  • }× 3
  • ,× 2
  • -× 1

More JavaScript examples at level 5

← JavaScript typing practice