Last active
August 28, 2020 15:19
-
-
Save PatrickJS/db2dd64163d581a9bfa918dab771475d 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
export class LRU extends Map { | |
constructor(private max: number) { | |
super(); | |
} | |
/** | |
* Attemps to retrieve a value from the cache | |
* @param key The key of the entry to return from the cache | |
* @returns the value associated to the input key or undefined | |
*/ | |
public get<T, V>(key: T): V | undefined { | |
const item = super.get(key); | |
if (!item) return undefined; | |
this.remove(key); | |
super.set(key, item); | |
return item; | |
} | |
/** | |
* Removes the entry | |
* @param key key is used to remove from the cache | |
*/ | |
// public remove(key: string): void { | |
// super.delete(key); | |
// } | |
// just use remove | |
/** | |
* Adds or updates an entry in the cache | |
* | |
* @param key new entry key | |
* @param value new entry value | |
*/ | |
public set<T, V>(key: T, value: V): this { | |
if (super.has(key)) super.remove(key); | |
else if (super.size === this.max) super.remove(this._first()); | |
super.set(key, value); | |
return this; | |
} | |
/** | |
* Get the oldest entry in the cache | |
* @returns value of the oldest entry | |
*/ | |
private _first() { | |
return super.keys().next().value; | |
} | |
} | |
export default LRU; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment