Last active
June 6, 2022 21:59
-
-
Save WebReflection/8ecdda99be08ffee767f05408a560204 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
// Least Recently Used | |
class LRUMap extends Map { | |
constructor(length) { | |
super().length = length; | |
} | |
_(key) { | |
const value = super.get(key); | |
super.delete(key); | |
super.set(key, value); | |
return value; | |
} | |
has(key) { | |
const result = super.has(key); | |
if (result) | |
this._(key); | |
return result; | |
} | |
get(key) { | |
return super.has(key) ? this._(key) : void 0; | |
} | |
set(key, value) { | |
super.delete(this.size < this.length ? key : super.keys().next().value); | |
return super.set(key, value); | |
} | |
} |
My thinking with the simplified version, is that you have length
(capacity) .set(...)
operations before a key goes away, without penalizing every .has(...)
or .get(...)
operation each time, so that the big class is always slow on .has
and .get
while the simplified one has slow path only on set
, which is usually for new entries in the cache, while old entries could be either manually re-set, if needed, but won't impact performance on get
and has
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simplified version that position only on set: