Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created February 16, 2020 17:06
Show Gist options
  • Save lastguest/d1630ae1cdb407aac723e05b19cf0193 to your computer and use it in GitHub Desktop.
Save lastguest/d1630ae1cdb407aac723e05b19cf0193 to your computer and use it in GitHub Desktop.
Memoization decorator for javascript functions
/*
function memoize(f) {
return function(...p){
this._cache = this._cache || []
var k = p.join('|')
return this._cache[k] || (this._cache[k] = f(...p))
}
}
*/
const memoize=(f)=>(...p)=>(this._=this._||[])[k=p.join('|')]||(this._[k]=f(...p))
/** EXAMPLE **/
function foo(index) {
// Return a non-determonistic value (for testing purposes)
return "" + index + ":" + (Math.random()*100000|0)
}
// Add memoization to foo function
foo = memoize(foo)
console.log(
foo(1), // RANDOM VALUE (A)
foo(1), // SAME as A
foo(2), // RANDOM VALUE (B)
foo(3), // RANDOM VALUE (C)
foo(1), // SAME as A
foo(1), // SAME as A
foo(3) // SAME as C
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment