Skip to content

Instantly share code, notes, and snippets.

@ivomarsan
Created July 12, 2018 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivomarsan/66341094d955b961010a972aa4edcf60 to your computer and use it in GitHub Desktop.
Save ivomarsan/66341094d955b961010a972aa4edcf60 to your computer and use it in GitHub Desktop.
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
@ivomarsan
Copy link
Author

  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment