Created
December 28, 2019 07:52
-
-
Save bhaveshdaswani93/7f1bf5510698fc98ed3ed42941351442 to your computer and use it in GitHub Desktop.
In this gist i will try to explain memoization in javascript
This file contains 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 notMemoized = (x) => { | |
return x*2; | |
} | |
notMemoized(2); // 4 | |
notMemoized(2); // 4 | |
// every time we run the function the multiplication code get executed which can be optimized by memoization | |
const memoizedFn = () => { | |
const cache = {}; | |
return (x) => { | |
if( x in cache ) { | |
return cache[x]; | |
} else { | |
return x*2; | |
} | |
} | |
} | |
const multiply = memoizedFn(); | |
multiply(2); // 4 | |
multiply(2); // 4 return from cache as the parameter is same so the return value is memoized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment