Skip to content

Instantly share code, notes, and snippets.

@adong
Created October 23, 2018 18:03
Show Gist options
  • Save adong/8aa321fb07726710573e3422183821ad to your computer and use it in GitHub Desktop.
Save adong/8aa321fb07726710573e3422183821ad to your computer and use it in GitHub Desktop.
Memoize function
function memoize(func) {
var memo = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments); // what if func(1,2,3) needs to be treated as the same as func(2,3,1)
if (args in memo) {
return memo[args]
} else {
return (memo[args] = func.apply(this, args);
}
}
}
/*
Reference
1. https://medium.freecodecamp.org/understanding-memoize-in-javascript-51d07d19430e
2. https://www.sitepoint.com/implementing-memoization-in-javascript/
Someone can also reference lodash memozie function as well
https://github.com/lodash/lodash/tree/4.1.2-npm-packages/lodash.memoize
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment