Last active
October 5, 2017 01:59
-
-
Save suissa/e81f7ec7858ebef230acf52127a9f50e to your computer and use it in GitHub Desktop.
Memoized pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const memoize = ( fn ) => { | |
const cache = {} | |
return function mfn () { | |
const args = [].slice.call( arguments ) | |
const key = JSON.stringify( args ) | |
return key in cache | |
? cache[ key ] | |
: cache[ key ] = fn.apply( this, args ) | |
} | |
} | |
const fib = ( n ) => | |
( n < 2 ) | |
? n | |
: fib( n - 1 ) + fib( n - 2 ) | |
console.time( 'fib' ) | |
const tfib = memoize( fib ) | |
console.log( tfib( 43 ) ) | |
console.timeEnd( 'fib' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment