Skip to content

Instantly share code, notes, and snippets.

@bhaveshdaswani93
Created December 28, 2019 07:52
Show Gist options
  • Save bhaveshdaswani93/7f1bf5510698fc98ed3ed42941351442 to your computer and use it in GitHub Desktop.
Save bhaveshdaswani93/7f1bf5510698fc98ed3ed42941351442 to your computer and use it in GitHub Desktop.
In this gist i will try to explain memoization in javascript
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