Memoization Pattern in JavaScript

Level 5500 keystrokes

This implements memoization to cache function results for performance.

JavaScript code

// Memoize: caches results of expensive function calls
// Returns cached result for same arguments
1function memoize(fn) {
// Map to store cached results
// Key: serialized arguments, Value: result
2 const cache = new Map();
3
4 return function(...args) {
// Create a unique key from arguments
5 const key = JSON.stringify(args);
// Check if result is already cached
6 if (cache.has(key)) {
7 console.log("Cache hit!");
8 return cache.get(key);
9 }
// Not cached - compute the result
10 console.log("Computing...");
11 const result = fn.apply(this, args);
// Store in cache for future calls
12 cache.set(key, result);
13 return result;
14 };
15}
16
// Expensive recursive function without memoization
17function fibonacci(n) {
18 if (n <= 1) return n;
19 return fibonacci(n - 1) + fibonacci(n - 2);
20}
21
// Create memoized version
22const memoFib = memoize(fibonacci);
// First call - computes and caches
23console.log(memoFib(10));
// Second call with same args - returns cached
24console.log(memoFib(10));
// Different args - computes and caches
25console.log(memoFib(5));

Output

Computing...
55
Cache hit!
55
Computing...
5
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.

  • (× 22
  • )× 22
  • .× 16
  • ;× 15
  • =× 5
  • "× 4
  • {× 4
  • }× 4
  • -× 2
  • ,× 2

More JavaScript examples at level 5

← JavaScript typing practice