← All topics

JS Machine Coding Questions — Implementations You Must Know

JavaScriptMachine CodingClosuresFunctional ProgrammingInterview

Memoize

1 / 16

1function memoize(fn) { 2 const cache = new Map(); 3 return function (...args) { 4 const key = JSON.stringify(args); 5 if (cache.has(key)) return cache.get(key); 6 const result = fn.apply(this, args); 7 cache.set(key, result); 8 return result; 9 }; 10} 11 12const factorial = memoize(function f(n) { 13 return n <= 1 ? 1 : n * f(n - 1); 14}); 15factorial(5); // computed → 120 16factorial(5); // from cache → 120