Skip to content

Instantly share code, notes, and snippets.

@cawa-93
Created June 16, 2021 09:08
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 cawa-93/a2e5970c4083e8b485f02c49cd85310a to your computer and use it in GitHub Desktop.
Save cawa-93/a2e5970c4083e8b485f02c49cd85310a to your computer and use it in GitHub Desktop.
Implementation of JavaScript `Map` with `size` limit
export class MapWithLimit<K = any, V = any> extends Map<K, V> {
readonly #limit: number
constructor(limit = 10, entries?: readonly (readonly [K, V])[] | null) {
super(entries);
this.#limit = limit;
}
set(key: K, value: V): this {
if (this.size + 1 > this.#limit) {
const firstKey = this.keys().next().value;
if (firstKey) {
this.delete(firstKey);
}
}
super.set(key, value);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment