import { RBTree } from "../tree/red-black-tree.mjs"; import type { CacheMap, Comparator } from "../interfaces/schema.mjs"; import { match } from "../common/option.mjs"; import { always, F, T } from "../../functions/wrapper.mjs"; interface Entry { key: K; value?: V; } export class OrderedMap implements CacheMap { #tree: RBTree>; constructor(comparator: Comparator) { this.#tree = new RBTree((a, b) => comparator(a.key, b.key)); } get(key: K): V | undefined { return match( this.#tree.search({ key }), (entry) => entry.value!, always(undefined) ); } has(key: K): boolean { return match(this.#tree.search({ key }), T, F); } set(key: K, value: V): this { const [entry, exist] = this.#tree.insert({ key, value }); if (exist) { entry.value = value; } return this; } delete(key: K): boolean { return this.#tree.erase({ key }); } }