@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
84 lines (83 loc) • 2.58 kB
TypeScript
import type { Comparator } from '../types.js';
export interface KeySortedMapOptions<K> {
/**
* Defaults to undefined.
* Undefined (default comparator) works well for String keys.
* For Number keys - use comparators.numericAsc (or desc),
* otherwise sorting will be wrong (lexicographic).
*/
comparator?: Comparator<K>;
}
/**
* Maintains sorted array of keys.
* Sorts **on insertion**, not on retrieval.
*
* - set(): O(log n) search + O(n) splice only when inserting a NEW key
* - get/has: O(1)
* - delete: O(log n) search + O(n) splice if present
* - iteration: O(n) over pre-sorted keys (no sorting at iteration time)
*
* @experimental
*/
export declare class KeySortedMap<K, V> implements Map<K, V> {
#private;
private readonly map;
constructor(entries?: [K, V][], opt?: KeySortedMapOptions<K>);
/**
* Convenience way to create KeySortedMap from object.
*/
static of<V>(obj: Record<any, V>): KeySortedMap<string, V>;
get size(): number;
clear(): void;
has(key: K): boolean;
get(key: K): V | undefined;
/**
* Allows to set multiple key-value pairs at once.
*/
setMany(obj: Record<any, V>): this;
/**
* Insert or update. Keeps keys array sorted at all times.
* Returns this (Map-like).
*/
set(key: K, value: V): this;
/**
* Delete by key. Returns boolean like Map.delete.
*/
delete(key: K): boolean;
/**
* Iterables (Map-compatible), all in sorted order.
*/
keys(): MapIterator<K>;
values(): MapIterator<V>;
entries(): MapIterator<[K, V]>;
[Symbol.iterator](): MapIterator<[K, V]>;
toString(): string;
[Symbol.toStringTag]: string;
/**
* Zero-allocation callbacks over sorted data (faster than spreading to arrays).
*/
forEach(cb: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
firstKeyOrUndefined(): K | undefined;
firstKey(): K;
lastKeyOrUndefined(): K | undefined;
lastKey(): K;
firstValueOrUndefined(): V | undefined;
firstValue(): V;
lastValueOrUndefined(): V | undefined;
lastValue(): V;
firstEntryOrUndefined(): [K, V] | undefined;
firstEntry(): [K, V];
lastEntryOrUndefined(): [K, V] | undefined;
lastEntry(): [K, V];
toJSON(): Record<string, V>;
toObject(): Record<string, V>;
/**
* Clones the KeySortedMap into ordinary Map.
*/
toMap(): Map<K, V>;
/**
* lowerBound: first index i s.t. keys[i] >= target
*/
private lowerBound;
private sortKeys;
}