Created
July 12, 2018 12:44
-
-
Save ivomarsan/66341094d955b961010a972aa4edcf60 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
let memoize = fn => { | |
let cache = {}; | |
return (...args) => { | |
let stringifiedArgs = JSON.stringify(args); | |
let result = cache[stringifiedArgs] = cache[stringifiedArgs] || fn(...args); | |
return result; | |
}; | |
}; | |
let pureAdd = (x,y) => { return x + y }; // pure function | |
let memoizedAdd = memoize(pureAdd); // memoized pure function | |
memoizedAdd(3,4) // 7 | |
memoizedAdd(3,4) // 7 | |
// efficient and consistent! | |
//By - Jonathan Schapiro | |
//Link: https://medium.com/front-end-hacking/today-i-learned-memoization-with-pure-functions-in-es6-33a4765518b5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 1
- Our memoize function accepts a fn to be memoized.Line 2
- We initialize a new cache for the fn passed in utilizing the, ever so powerful, closure scope.Line 3
- We return the memoized fn which accepts some number of args.Line 4
- We stringify the arguments passed to our memoized fn to be used as a “key” to our cache.Line 5
- We then check the cache for the value associated with that key. If the value associated with that key exists in the cache we assign it to result otherwise we call fn with the arguments passed to the memoized function and assign its value to the cache.Line 6
- Finally, we return the result.