Created
June 16, 2021 09:08
-
-
Save cawa-93/a2e5970c4083e8b485f02c49cd85310a to your computer and use it in GitHub Desktop.
Implementation of JavaScript `Map` with `size` limit
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 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