Skip to content

Instantly share code, notes, and snippets.

@ravecat
Last active October 17, 2020 20:39
Show Gist options
  • Save ravecat/7246ba1875d8b7c0b8d14daf0c78aba2 to your computer and use it in GitHub Desktop.
Save ravecat/7246ba1875d8b7c0b8d14daf0c78aba2 to your computer and use it in GitHub Desktop.
js
function Memoized() {}
const memoize = fn => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
console.log('Read from cache');
callback(record.err, record.data);
return;
}
fn(...args, (err, data) => {
cache.set(key, { err, data });
callback(err, data);
});
};
const fields = {
cache,
timeout: 0,
limit: 0,
size: 0,
maxSize: 0,
};
Object.setPrototypeOf(memoized, Memoized.prototype);
return Object.assign(memoized, fields);
};
Memoized.prototype.clear = function() {
this.cache.clear();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment