Last active
August 14, 2022 20:26
-
-
Save sebinsua/92ee597b1c28465520ed7b25de02cead to your computer and use it in GitHub Desktop.
This file contains 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 defaultCreateKey(args) { | |
return JSON.stringify(args); | |
} | |
class LruCache { | |
constructor(capacity = Infinity) { | |
this.capacity = capacity; | |
this.cache = new Map(); | |
} | |
has(key) { | |
return this.cache.has(key); | |
} | |
get(key) { | |
const value = this.cache.get(key); | |
this.cache.delete(key); | |
this.cache.set(key, value); | |
return value; | |
} | |
set(key, value) { | |
if (this.cache.size + 1 > this.capacity) { | |
const key = this._getLeastRecentlyUsedKey(); | |
if (key) { | |
// console.log("evicting key:", key); | |
this.cache.delete(key); | |
} | |
} | |
this.cache.delete(key); | |
this.cache.set(key, value); | |
} | |
_getLeastRecentlyUsedKey() { | |
for (const [key] of this.cache) { | |
return key; | |
} | |
return undefined; | |
} | |
} | |
function memoize( | |
fn, | |
{ | |
createKey = defaultCreateKey, | |
size = Infinity, | |
cache = new LruCache(size) | |
} = {} | |
) { | |
return (...args) => { | |
const key = createKey(args); | |
if (cache.has(key)) { | |
return cache.get(key); | |
} | |
cache.set(key, fn(...args)); | |
return cache.get(key); | |
}; | |
} | |
const newFn = memoize((key) => Math.random(), { size: 3 }); | |
for (let key of [ | |
"key", | |
"key2", | |
"key3", | |
"key", | |
"key2", | |
"key4", | |
"key5", | |
"key3", | |
"key", | |
"key5" | |
]) { | |
console.log(key, newFn(key)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not using an LRU below but have shown a way of referrring to the inner function as a memoized function internally without needinig to know its memoized name.
See: https://codesandbox.io/s/vigilant-cerf-mbtyky?file=%2Fsrc%2Findex.js
(I learn this from: https://raganwald.com/2018/09/10/why-y.html)