UNPKG

@thi.ng/wasm-api

Version:

Generic, modular, extensible API bridge and infrastructure for hybrid JS & WebAssembly projects

89 lines 2.78 kB
import type { Maybe, Predicate, Range1_32 } from "@thi.ng/api"; import { IDGen } from "@thi.ng/idgen"; import type { ILogger } from "@thi.ng/logger"; export interface ObjectIndexOpts { /** * Human-readable name for index (used for logging, if any) */ name: string; /** * Optional logger instance */ logger: ILogger; /** * Number of bits for IDs, `[1,32]` range. * * @defaultValue 32 */ bits: Range1_32; } /** * Object cache with numeric ID handle management. * * @remarks * [Further reference](https://docs.thi.ng/umbrella/wasm-api/#md:object-indices--handles) */ export declare class ObjectIndex<T> { readonly name: string; logger?: ILogger; protected idgen: IDGen; protected items: T[]; constructor(opts?: Partial<ObjectIndexOpts>); keys(): Generator<number, void, unknown>; values(): Generator<T, void, unknown>; /** * Indexes given `item` and assigns it to the next available ID (which might * be a previously freed ID) and returns it. * * @param item */ add(item: T): number; /** * Similar to {@link ObjectIndex.add}, but first checks if `item` has * already been indexed and if so returns the ID of already indexed item * without adding `item` to the index again. Uses `equiv` for checking item * equality (by default: `===`). * * @remarks * Currently an O(n) implementation. * * @param item * @param equiv */ addUnique(item: T, equiv?: Predicate<T>): number; /** * Returns true if the given `id` is valid/active. * * @param id */ has(id: number): boolean; /** * First checks if given `id` is valid and if so frees it (for recycling) * and deletes its corresponding item. If `ensure` is true (default), throws * an error if the ID is invalid (otherwise returns false for invalid IDs). * * @param id * @param ensure */ delete(id: number, ensure?: boolean): boolean; /** * First checks if given `id` is valid and if so returns corresponding item. * If `ensure` is true (default), throws an error if the ID is invalid * (otherwise returns undefined for invalid IDs) * * @param id */ get(id: number): T; get(id: number, ensure: true): T; get(id: number, ensure: false): Maybe<T>; /** * Applies given predicate to all active items and returns ID of first * matching. If `ensure` is true (default), throws an error if the `pred` * didn't match anything (otherwise returns undefined). * * @param pred * @param ensure */ find(pred: Predicate<T>, ensure?: boolean): number | undefined; } //# sourceMappingURL=object-index.d.ts.map