Memoization Pattern in JavaScript
Level 5409 keystrokes
Memoization caches function results based on arguments to avoid redundant computations.
JavaScript code
// Define memoization higher-order function1function memoize(fn) { // Create cache using Map2 const cache = new Map(); // Return memoized function3 return function(...args) { // Create cache key from arguments4 const key = JSON.stringify(args); // Check if result is cached5 if (cache.has(key)) { // Log cache hit6 console.log("Cache hit"); // Return cached result7 return cache.get(key);8 } // Log that we're computing9 console.log("Computing"); // Call original function10 const result = fn.apply(this, args); // Store result in cache11 cache.set(key, result); // Return computed result12 return result;13 };14}// Create a memoized factorial// The recursive call also goes through the memoized version, so 5..1 are each cached15const factorial = memoize(n => n <= 1 ? 1 : n * factorial(n - 1));// First call: prints "Computing" 5 times (n = 5..1), then 12016console.log(factorial(5));// Second call: "Cache hit", then 120 without recomputing17console.log(factorial(5));Output
Computing Computing Computing Computing Computing 120 Cache hit 120
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