Last active
October 17, 2020 20:39
-
-
Save ravecat/7246ba1875d8b7c0b8d14daf0c78aba2 to your computer and use it in GitHub Desktop.
js
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
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