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 arguments1function memoize(fn) { // Map to store cached results // Key: serialized arguments, Value: result2 const cache = new Map();3 4 return function(...args) { // Create a unique key from arguments5 const key = JSON.stringify(args); // Check if result is already cached6 if (cache.has(key)) {7 console.log("Cache hit!");8 return cache.get(key);9 } // Not cached - compute the result10 console.log("Computing...");11 const result = fn.apply(this, args); // Store in cache for future calls12 cache.set(key, result);13 return result;14 };15}16 // Expensive recursive function without memoization17function fibonacci(n) {18 if (n <= 1) return n;19 return fibonacci(n - 1) + fibonacci(n - 2);20}21 // Create memoized version22const memoFib = memoize(fibonacci);// First call - computes and caches23console.log(memoFib(10));// Second call with same args - returns cached24console.log(memoFib(10));// Different args - computes and caches25console.log(memoFib(5));Output
Computing... 55 Cache hit! 55 Computing... 5
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