Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active August 28, 2020 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatrickJS/db2dd64163d581a9bfa918dab771475d to your computer and use it in GitHub Desktop.
Save PatrickJS/db2dd64163d581a9bfa918dab771475d to your computer and use it in GitHub Desktop.
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