UNPKG

@toolbox-ts/dsa

Version:
91 lines 2.81 kB
import { Node } from "../node/index.js"; import { Size } from "./size/index.js"; /** * Iterates over node details in a structure, starting from * a given node and following a pointer key. * Yields each node's detail and its index in the traversal. */ export function* genericDetailIterator(startNode, pointerKey) { let current = startNode; let index = 0; while (current) { yield { detail: current.detail, index: index++ }; current = current[pointerKey]; if (current?.id === startNode?.id) break; } } /** * Creates a new structure instance with node and size management. * @param config - Structure configuration */ export const create = ({ type, nodeManagerCfg, sizing = {}, }) => { const { maxSize = Infinity, assertErrorMsgs = {} } = sizing; const { type: _type, ...nodeCfg } = nodeManagerCfg; const { anchors, create: createNode, ...node } = Node.create[_type](nodeCfg); const ids = new Set(); const size = Size.create({ calculate: () => ids.size, assertErrorMsgs, maxSize, }); const toString = () => `Structure { type: "${type}", nodeType: "${node.type}", anchors: [${anchors.keys.map((key) => `"${key}"`).join(", ")}], size: ${size.get()} / ${size.getMaxSize()} nodes }`; function add(detail, cb) { size.assert.notFull(); return size.mutate(() => { if (ids.has(detail.id)) throw new Error(`Node with ID ${detail.id} already exists.`); const n = createNode(detail); ids.add(n.id); return cb?.(n); }); } const remove = (node, cb) => node === undefined ? undefined : size.mutate(() => { if (!ids.has(node.id)) throw new Error(`Node with ID ${node.id} does not exist.`); const result = cb?.(node); ids.delete(node.id); return result; }); const reset = () => { anchors.reset(); ids.clear(); size.clearCache(); }; return { node, anchors, toString, type, size, add, remove, has: (id) => ids.has(id), reset, }; }; /** * Extracts the recommended public API from a structure instance. * Only exposes safe and useful methods for consumers. */ export const extractPublicAPI = (struct) => ({ type: struct.type, toString: struct.toString, isEmpty: struct.size.is.empty, isFull: struct.size.is.full, getSize: struct.size.get, getMaxSize: struct.size.getMaxSize, setMaxSize: struct.size.setMaxSize, getSizeMode: struct.size.getSizeMode, getCapacity: struct.size.getCapacity, reset: struct.reset, has: struct.has, }); //# sourceMappingURL=structure.js.map