Skip to content

Instantly share code, notes, and snippets.

@cameronbourke
Created January 10, 2016 21:18
Show Gist options
  • Save cameronbourke/49e798be4f2add8f27cf to your computer and use it in GitHub Desktop.
Save cameronbourke/49e798be4f2add8f27cf to your computer and use it in GitHub Desktop.
const memoize = (fn) => {
let cache = {}, key;
return (...args) => {
key = JSON.stringify(args);
return cache[key] || (cache[key] = fn.call(null, ...args));
}
};
@iamaamir
Copy link

iamaamir commented Aug 19, 2020

what if the function do not have any arument ?
the output cache may look like { '[]': '...'}

@cameronbourke
Copy link
Author

Hey! That's a great point. I guess it doesn't make sense to talk about memoizing functions that do not take any arguments. The other problem with this approach is that JSON.stringify() is a relatively slow call to make!

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