Created
October 23, 2018 18:03
-
-
Save adong/8aa321fb07726710573e3422183821ad to your computer and use it in GitHub Desktop.
Memoize function
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
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