Memoization in JavaScript
Level 4242 keystrokes
Memoization caches function results to avoid repeated expensive calculations.
JavaScript code
// Memoize wrapper function1function memoize(fn) { // Cache object to store results2 const cache = {}; // Return memoized function3 return (arg) => { // If arg is not cached yet, compute fn(arg) and store it4 if (!(arg in cache)) cache[arg] = fn(arg); // Return cached result5 return cache[arg];6 };7}// Create memoized square function that logs when calculating8const square = memoize(n => { console.log("calc"); return n * n; });// First call: calculates and caches9console.log(square(4));// Second call: returns cached result (no "calc" logged)10console.log(square(4));Output
calc 16 16
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