Some functions are expensive — a heavy calculation, a big search, a complex filter. If you call them twice with the same input, you get the same output, so why compute it twice? Memoization remembers past results and returns the cached answer instead of recalculating.
function memoize ( fn ) { const cache = new Map ( ) ; return function ( . . . args ) { const key = JSON . stringify ( args ) ; if ( cache . has ( key ) ) { return cache . get ( key ) ; } const result = fn ( . . . args ) ; cache . set ( key , result ) ; return result ; } ; }
function slowSquare ( n ) { console . log ( 'Computing...' ) ; return n * n ; }
const fastSquare = memoize ( slowSquare ) ; console . log ( fastSquare ( 5 ) ) ; // Computing... 25 console . log ( fastSquare ( 5 ) ) ; // 25 (from cache, no computing)
Enter fullscreen mode
Exit fullscreen mode
Memoization only works for pure functions — same input, same output, no side effects.…