Skip to content

Instantly share code, notes, and snippets.

@suissa
Last active October 5, 2017 01:59
Show Gist options
  • Save suissa/e81f7ec7858ebef230acf52127a9f50e to your computer and use it in GitHub Desktop.
Save suissa/e81f7ec7858ebef230acf52127a9f50e to your computer and use it in GitHub Desktop.
Memoized pattern
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