@mark1russell7/collections 0.9.8 → 0.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2 -2
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/events.ts +4 -3
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["fold","PRESENT","Tree.of","Tree.size","Tree.isEmpty","Tree.summary","Tree.height","Tree.at","Tree.summaryOf","Tree.concat","Tree.splitAt","Tree.split","Tree.search","Tree.locate","Tree.slice","Tree.splice","Tree.insert","Tree.remove","Tree.set","Tree.append","Tree.prepend","Tree.leaves","Tree.toArray","addEach","none","some","toArray","toSet","toMap","toList","toMap"],"sources":["../src/core/policies.ts","../src/core/middleware.ts","../src/core/events.ts","../src/core/removals.ts","../src/storage/listeners.ts","../src/order/rank.ts","../src/utils/defaults.ts","../src/impl/array-list.ts","../src/impl/array-deque.ts","../src/impl/hash-map.ts","../src/impl/linked-hash-map.ts","../src/impl/tree-map.ts","../src/impl/tree-set.ts","../src/impl/linked-list.ts","../src/impl/hash-set.ts","../src/impl/priority-queue.ts","../src/impl/summary-tree.ts","../src/core/capacity.ts","../src/behaviors/bounded.ts","../src/behaviors/readonly.ts","../src/behaviors/safe.ts","../src/behaviors/composite.ts","../src/behaviors/evented.ts","../src/behaviors/synchronized.ts","../src/behaviors/lru.ts","../src/behaviors/ttl.ts","../src/async/async-queue.ts","../src/async/channels.ts","../src/async/settled.ts","../src/async/semaphore.ts","../src/fx/iter.ts","../src/fx/collectors.ts","../src/utils/factories.ts","../src/utils/helpers.ts"],"sourcesContent":["/**\n * Policy types for configurable collection behaviors.\n *\n * Policies define how collections handle edge cases like overflow,\n * underflow, and eviction. These are used by behavior decorators\n * to give flexible, composable behavior.\n */\n\n// ============================================================================\n// Overflow Policies - what to do when a bounded collection is full\n// ============================================================================\n\n/**\n * Policy for handling overflow when adding to a full bounded collection.\n *\n * - 'throw': Throw an error when trying to add to a full collection\n * - 'drop-oldest': Remove the oldest element and add the new one\n * - 'drop-newest': Ignore the new element (don't add it)\n * - 'reject': Return false/None but don't throw (graceful failure)\n * - 'grow': Automatically increase capacity (becomes unbounded)\n * - 'block': For async collections, wait until space is available\n */\nexport type OverflowPolicy =\n | \"throw\"\n | \"drop-oldest\"\n | \"drop-newest\"\n | \"reject\"\n | \"grow\"\n | \"block\";\n\n/**\n * Context information given when overflow occurs.\n */\nexport interface OverflowContext<T> {\n /** The element that triggered the overflow. */\n readonly newElement: T;\n /** Current size of the collection. */\n readonly currentSize: number;\n /** Maximum capacity of the collection. */\n readonly capacity: number;\n /** Timestamp when overflow occurred. */\n readonly timestamp: number;\n}\n\n/**\n * Callback invoked when overflow occurs.\n * This function can log, record metrics or do custom handling.\n */\nexport type OverflowHandler<T> = (context: OverflowContext<T>) => void;\n\n// ============================================================================\n// Underflow Policies - what to do when removing from an empty collection\n// ============================================================================\n\n/**\n * Policy for handling underflow when removing from an empty collection.\n *\n * - 'throw': Throw an error when trying to remove from empty collection\n * - 'return-none': Return None/undefined (graceful failure)\n * - 'return-default': Give a default value given by user\n * - 'block': For async collections, wait until an element is available\n */\nexport type UnderflowPolicy =\n | \"throw\"\n | \"return-none\"\n | \"return-default\"\n | \"block\";\n\n/**\n * Context information given when underflow occurs.\n */\nexport interface UnderflowContext {\n /** The operation that triggered the underflow. */\n readonly operation: string;\n /** Timestamp when underflow occurred. */\n readonly timestamp: number;\n}\n\n/**\n * Callback invoked when underflow occurs.\n */\nexport type UnderflowHandler = (context: UnderflowContext) => void;\n\n// ============================================================================\n// Eviction Policies - how to choose which element to remove\n// ============================================================================\n\n/**\n * Policy for choosing which element to evict from a bounded collection.\n *\n * - 'lru': Least Recently Used - evict element not accessed for longest time\n * - 'lfu': Least Frequently Used - evict element accessed least often\n * - 'fifo': First In First Out - evict oldest inserted element\n * - 'lifo': Last In First Out - evict newest inserted element (stack-like)\n * - 'random': Evict a random element\n * - 'ttl': Time To Live - evict elements that have expired\n * - 'priority': Evict element with lowest priority\n * - 'custom': User-provided eviction function\n */\nexport type EvictionPolicy =\n | \"lru\"\n | \"lfu\"\n | \"fifo\"\n | \"lifo\"\n | \"random\"\n | \"ttl\"\n | \"priority\"\n | \"custom\";\n\n/**\n * Metadata tracked for eviction decisions.\n */\nexport interface EvictionMetadata {\n /** When the element was inserted. */\n readonly insertedAt: number;\n /** When the element was last accessed. */\n lastAccessedAt: number;\n /** How many times the element has been accessed. */\n accessCount: number;\n /** Time-to-live expiration timestamp (if applicable). */\n readonly expiresAt?: number;\n /** Priority value (higher = more important, if applicable). */\n readonly priority?: number;\n}\n\n/**\n * Information about an element that can be evicted.\n */\nexport interface EvictionCandidate<T> {\n /** The element value. */\n readonly element: T;\n /** Eviction metadata for this element. */\n readonly metadata: EvictionMetadata;\n}\n\n/**\n * Custom eviction function.\n * Given candidates, gives the element to evict.\n */\nexport type EvictionSelector<T> = (\n candidates: EvictionCandidate<T>[]\n) => T | undefined;\n\n// ============================================================================\n// Retry Policies - for async operations\n// ============================================================================\n\n/**\n * Policy for retrying failed async operations.\n */\nexport interface RetryPolicy {\n /** Maximum number of retry tries. */\n readonly maxAttempts: number;\n /** Initial delay in milliseconds. */\n readonly initialDelay: number;\n /** Backoff strategy. */\n readonly backoff: \"none\" | \"linear\" | \"exponential\";\n /** Maximum delay cap (for backoff). */\n readonly maxDelay?: number;\n /** Jitter to add randomness and avoid thundering herd. */\n readonly jitter?: boolean;\n}\n\n/**\n * Context for retry decisions.\n */\nexport interface RetryContext {\n /** Current try number (1-indexed). */\n readonly attempt: number;\n /** The error that caused the retry. */\n readonly error: unknown;\n /** Elapsed time since first try. */\n readonly elapsedMs: number;\n}\n\n/**\n * Callback to determine if an error is retryable.\n */\nexport type RetryPredicate = (context: RetryContext) => boolean;\n\n// ============================================================================\n// Conflict Resolution Policies - for concurrent modifications\n// ============================================================================\n\n/**\n * Policy for resolving conflicts when same key is changed concurrently.\n *\n * - 'last-write-wins': Most recent write takes precedence\n * - 'first-write-wins': First write takes precedence\n * - 'merge': Call merge function to combine values\n * - 'throw': Throw an error on conflict\n */\nexport type ConflictResolutionPolicy =\n | \"last-write-wins\"\n | \"first-write-wins\"\n | \"merge\"\n | \"throw\";\n\n/**\n * Function to merge conflicting values.\n */\nexport type MergeFunction<T> = (current: T, incoming: T) => T;\n\n// ============================================================================\n// Compaction Policies - for memory management\n// ============================================================================\n\n/**\n * Policy for when to compact internal storage.\n */\nexport interface CompactionPolicy {\n /** The collection compacts when the used part of its capacity is less than this ratio, from 0 to 1. */\n readonly minLoadFactor?: number;\n /** The collection compacts when its wasted space is more than this number of elements. */\n readonly maxWastedSpace?: number;\n /** When it is true, the collection compacts at each removal. */\n readonly autoCompact?: boolean;\n}\n\n// ============================================================================\n// Growth Policies - for dynamic capacity\n// ============================================================================\n\n/**\n * Policy for how to grow capacity when needed.\n */\nexport interface GrowthPolicy {\n /** Growth strategy. */\n readonly strategy: \"double\" | \"linear\" | \"golden-ratio\" | \"custom\";\n /** For linear growth, how many elements to add. */\n readonly linearIncrement?: number;\n /** For custom growth, a function to calculate new capacity. */\n readonly customGrowth?: (currentCapacity: number) => number;\n /** Maximum capacity limit (prevent unbounded growth). */\n readonly maxCapacity?: number;\n}\n\n// ============================================================================\n// Validation Policies - for type checking\n// ============================================================================\n\n/**\n * Validation action when an invalid element is encountered.\n *\n * - 'throw': Throw an error\n * - 'drop': Silently drop the invalid element\n * - 'coerce': Try to coerce to valid type\n * - 'log': Log a warning and continue\n */\nexport type ValidationPolicy = \"throw\" | \"drop\" | \"coerce\" | \"log\";\n\n/**\n * Context for validation failures.\n */\nexport interface ValidationContext<T> {\n /** The invalid element. */\n readonly element: T;\n /** Validation error message/details. */\n readonly error: unknown;\n /** The operation that triggered validation. */\n readonly operation: string;\n}\n\n/**\n * Callback invoked on validation failures.\n */\nexport type ValidationHandler<T> = (context: ValidationContext<T>) => void;\n\n// ============================================================================\n// Default policies\n// ============================================================================\n\n/**\n * Default overflow policy: throw an error.\n */\nexport const DEFAULT_OVERFLOW_POLICY: OverflowPolicy = \"throw\";\n\n/**\n * Default underflow policy: throw an error.\n */\nexport const DEFAULT_UNDERFLOW_POLICY: UnderflowPolicy = \"throw\";\n\n/**\n * Default eviction policy: FIFO (oldest first).\n */\nexport const DEFAULT_EVICTION_POLICY: EvictionPolicy = \"fifo\";\n\n/**\n * Default retry policy: 3 tries with exponential backoff.\n */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n initialDelay: 100,\n backoff: \"exponential\",\n maxDelay: 5000,\n jitter: true,\n};\n\n/**\n * Default conflict resolution: last write wins.\n */\nexport const DEFAULT_CONFLICT_POLICY: ConflictResolutionPolicy =\n \"last-write-wins\";\n\n/**\n * Default growth policy: double capacity.\n */\nexport const DEFAULT_GROWTH_POLICY: GrowthPolicy = {\n strategy: \"double\",\n maxCapacity: Number.MAX_SAFE_INTEGER,\n};\n\n/**\n * Default validation policy: throw on invalid.\n */\nexport const DEFAULT_VALIDATION_POLICY: ValidationPolicy = \"throw\";\n","/**\n * Middleware composition system for collections.\n *\n * This module gives the core composition mechanism. With it, behaviors go in layers\n * on top of collections with the decorator pattern.\n *\n * The mechanism is for synchronous collection operations. The collection instance itself\n * is the context, so a behavior needs no explicit context object.\n *\n * @example\n * const list = compose(\n * safeList<number>(),\n * eventedList<number>(),\n * boundedList<number>({ capacity: 100 })\n * )(arrayList<number>())\n */\n\nimport type { Collection } from \"../interfaces/collection.js\";\nimport { compose as fold, type Chain, type Layer, type Stacked } from \"./layers.js\";\n\n/**\n * A middleware is a function that takes a collection and gives\n * an enhanced version of that collection.\n *\n * This maps to the unified middleware pattern where:\n * - The \"context\" is the collection itself (passed directly, not in a context object)\n * - Execution is synchronous (no Promises)\n * - Type transformation is tracked through In -> Out\n *\n * Middleware can:\n * - Intercept method calls\n * - Add new capabilities\n * - Transform inputs/outputs\n * - Delegate to the next layer\n *\n * @template In The input collection type\n * @template Out The output collection type (defaults to In if not specified)\n */\nexport type Middleware<In = any, Out extends In = In> = (next: In) => Out;\n\n/**\n * Composes multiple middleware layers into a single enhancer function.\n *\n * This function uses reduceRight to make an \"onion\" pattern where the first middleware\n * is the outermost layer (runs first when calling into the collection).\n *\n * The type system properly tracks capability additions through composition.\n *\n * @example\n * // Layer order (outer to inner):\n * // 1. safe - converts throws to Option/Result\n * // 2. evented - emits events on mutations\n * // 3. bounded - enforces capacity limits\n * // 4. base - the underlying ArrayList\n * const enhancer = compose(\n * safeList<number>(),\n * eventedList<number>(),\n * boundedList<number>({ capacity: 100 })\n * )\n * const list = enhancer(arrayList<number>())\n * // Type: List<number> & SafeCollection & EventedCollection & BoundedCollection\n *\n * @param layers The middleware layers to compose\n * @returns A function that applies all layers to a base collection\n */\nexport function compose<const L extends readonly Layer[]>(...layers: L & Chain<L>): Stacked<L> {\n return fold(...(layers as readonly Layer[])) as unknown as Stacked<L>;\n}\n\n/**\n * Utility to check if a collection has a specific capability.\n * Useful for middleware that wants to conditionally enhance behavior.\n *\n * @example\n * if (hasCapability(collection, 'on')) {\n * // Collection supports events\n * collection.on('add', handler)\n * }\n */\nexport const hasCapability = <C extends Collection<any>, K extends keyof any>(\n collection: C,\n capability: K\n): collection is C & Record<K, unknown> => {\n return capability in collection;\n};\n\n/**\n * Marker interface for collections that support events.\n * Middleware can use this to detect event capability.\n */\nexport interface Evented<E extends Record<string, any>> {\n /**\n * This method subscribes a listener to an event.\n * @returns Unsubscribe function\n */\n on<K extends keyof E>(event: K, handler: (payload: E[K]) => void): () => void;\n\n /**\n * This method emits an event. Only the middleware calls it.\n * @internal\n */\n emit?<K extends keyof E>(event: K, payload: E[K]): void;\n}\n\n/**\n * Marker interface for collections that support async operations.\n */\nexport interface Async<T> {\n /**\n * Async iterator for consuming elements.\n */\n [Symbol.asyncIterator](): AsyncIterator<T>;\n}\n\n/**\n * Marker interface for collections that are bounded.\n */\nexport interface BoundedCollection {\n /** Maximum capacity */\n readonly capacity: number;\n /** If collection is at capacity */\n readonly isFull: boolean;\n /** Remaining space */\n readonly remainingCapacity: number;\n}\n\n/**\n * Marker interface for collections that support safe (Option/Result) operations.\n */\nexport interface SafeCollection {\n /**\n * Namespace for safe operations that return Option/Result instead of throwing.\n */\n readonly safe: unknown;\n}\n\n/**\n * This type gives the element type of a collection.\n */\nexport type ElementType<C> = C extends {\n [Symbol.iterator](): Iterator<infer T>;\n}\n ? T\n : C extends { get(index: number): infer T }\n ? T\n : C extends { peek(): infer T }\n ? T\n : never;\n\n/**\n * This type changes each method of a type so that it gives its async equivalent.\n */\nexport type Asyncify<C> = {\n [K in keyof C]: C[K] extends (...args: infer Args) => infer R\n ? (...args: Args) => Promise<R>\n : C[K];\n};\n\n/**\n * Helper to make a proxy that intercepts method calls.\n * Useful for implementing middleware that needs to wrap method invocations.\n *\n * @example\n * const logged = interceptMethods(collection, (target, method, args) => {\n * console.log(`Calling ${String(method)} with`, args)\n * const result = Reflect.apply(target[method], target, args)\n * console.log(`Result:`, result)\n * return result\n * })\n */\nexport const interceptMethods = <C extends object>(\n target: C,\n interceptor: (target: C, method: keyof C, args: unknown[]) => unknown\n): C => {\n return new Proxy(target, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver);\n if (typeof value === \"function\" && typeof prop === \"string\") {\n return function (this: unknown, ...args: unknown[]) {\n return interceptor(t, prop as keyof C, args);\n };\n }\n return value;\n },\n });\n};\n\n/**\n * Helper to make a readonly view of a collection by blocking mutating methods.\n *\n * @param mutatingMethods Set of method names that the middleware blocks\n * @param errorMessage Custom error message to throw\n */\nexport const blockMethods = <C extends object>(\n target: C,\n mutatingMethods: Set<string | symbol>,\n errorMessage: string = \"Operation not allowed\"\n): C => {\n return new Proxy(target, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver);\n if (typeof value === \"function\" && mutatingMethods.has(prop)) {\n return () => {\n throw new Error(errorMessage);\n };\n }\n return value;\n },\n });\n};\n\n/**\n * Helper to delegate method calls to a target while maintaining correct context.\n * Useful when wrapping collections.\n */\nexport const delegate = <C extends object, T extends C>(\n target: T,\n wrapper: Partial<C>\n): C => {\n return new Proxy(target, {\n get(t, prop, receiver) {\n // If wrapper has the property, use it\n if (prop in wrapper) {\n return Reflect.get(wrapper, prop, receiver);\n }\n // Otherwise delegate to target\n const value = Reflect.get(t, prop, receiver);\n // Bind methods to maintain correct 'this' context\n if (typeof value === \"function\") {\n return value.bind(t);\n }\n return value;\n },\n }) as C;\n};\n\n/**\n * Utility type to add optional capabilities to a collection type.\n */\nexport type WithCapability<C, Cap> = C & Cap;\n\n/**\n * Builder pattern helper for fluent API construction.\n *\n * @example\n * class ListBuilder<T> {\n * private middleware: Middleware<List<T>>[] = []\n *\n * bounded(capacity: number) {\n * this.middleware.push(boundedList({ capacity }))\n * return this\n * }\n *\n * evented() {\n * this.middleware.push(eventedList())\n * return this\n * }\n *\n * build(): List<T> {\n * return compose(...this.middleware)(arrayList<T>())\n * }\n * }\n */\nexport abstract class CollectionBuilder<C> {\n protected middleware: Middleware<C>[] = [];\n\n /**\n * This method applies a custom middleware.\n */\n use(middleware: Middleware<C>): this {\n this.middleware.push(middleware);\n return this;\n }\n\n /**\n * This method builds the final collection: it composes all middleware with the base.\n */\n abstract build(): C;\n}\n\n/**\n * Utility to make a middleware that only enhances specific methods.\n *\n * @example\n * const logAdd = enhanceMethod('add', (original, args) => {\n * console.log('Adding:', args[0])\n * return original(...args)\n * })\n */\nexport const enhanceMethod = <C extends object, K extends keyof C & string>(\n methodName: K,\n enhancer: (\n original: C[K] extends (...args: infer Args) => infer R\n ? (...args: Args) => R\n : never,\n args: C[K] extends (...args: infer Args) => any ? Args : never\n ) => C[K] extends (...args: any[]) => infer R ? R : never\n): Middleware<C> => {\n return (next: C): C => {\n type MethodArgs = C[K] extends (...args: infer Args) => any ? Args : never;\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === methodName && typeof value === \"function\") {\n return function (this: unknown, ...args: unknown[]) {\n return enhancer(value.bind(target), args as MethodArgs);\n };\n }\n return value;\n },\n });\n };\n};\n\n/**\n * This function combines multiple middleware into a single middleware.\n * Useful for making reusable middleware bundles.\n *\n * Bundle has the same composition semantics as compose - the first middleware\n * is the outermost layer, and types are tracked through the chain.\n *\n * @example\n * const standardBehaviors = bundle(\n * boundedList<number>({ capacity: 1000 }),\n * eventedList<number>(),\n * safeList<number>()\n * )\n *\n * const list = compose(standardBehaviors)(arrayList<number>())\n */\nexport const bundle: typeof compose = compose;\n","/**\n * Typed event emitter system for collections.\n *\n * This function gives a lightweight, type-safe event system for mutation events\n * and other observable behavior. Events are strongly typed using\n * TypeScript's mapped types.\n */\n\n/**\n * A listener function that receives an event payload.\n */\nexport type Listener<P> = (payload: P) => void;\n\n/**\n * A function to unsubscribe from an event.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Event map defining event names and their payload types.\n *\n * @example\n * interface MyEvents {\n * add: { value: number; index: number }\n * remove: { value: number }\n * clear: {}\n * }\n */\nexport type EventMap = Record<string, any>;\n\n/**\n * Type-safe event emitter.\n *\n * This class supports subscribing to events, emitting events, and managing listeners.\n * All event names and payloads are type-checked at compile time.\n *\n * @example\n * interface ListEvents<T> {\n * add: { value: T; index: number }\n * remove: { value: T; index: number }\n * clear: {}\n * }\n *\n * const emitter = new Emitter<ListEvents<number>>()\n *\n * const unsub = emitter.on('add', ({ value, index }) => {\n * console.log(`Added ${value} at ${index}`)\n * })\n *\n * emitter.emit('add', { value: 42, index: 0 })\n * unsub() // Unsubscribe\n */\nexport class Emitter<E extends EventMap> {\n private listeners = new Map<keyof E, Set<Listener<any>>>();\n\n /**\n * This method subscribes a listener to an event.\n *\n * @param event The event name\n * @param listener The callback to invoke when event is emitted\n * @returns A function to unsubscribe\n */\n on<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n listeners = new Set();\n this.listeners.set(event, listeners);\n }\n listeners.add(listener);\n\n // Return unsubscribe function\n return () => {\n listeners!.delete(listener);\n // Clean up empty sets\n if (listeners!.size === 0) {\n this.listeners.delete(event);\n }\n };\n }\n\n /**\n * This method subscribes a listener to an event, and unsubscribes it after the first emission.\n *\n * @param event The event name\n * @param listener The callback to invoke once\n * @returns A function to unsubscribe (in case you want to cancel before emission)\n */\n once<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {\n const wrappedListener: Listener<E[K]> = (payload) => {\n unsubscribe();\n listener(payload);\n };\n\n const unsubscribe = this.on(event, wrappedListener);\n return unsubscribe;\n }\n\n /**\n * This method emits an event to all registered listeners.\n *\n * @param event The event name\n * @param payload The event payload\n */\n emit<K extends keyof E>(event: K, payload: E[K]): void {\n const listeners = this.listeners.get(event);\n if (listeners) {\n // Create a snapshot to avoid issues if listeners modify the set\n const snapshot = Array.from(listeners);\n for (const listener of snapshot) {\n try {\n listener(payload);\n } catch (error) {\n // Log error but don't stop other listeners\n console.error(\n `Error in event listener for '${String(event)}':`,\n error\n );\n }\n }\n }\n }\n\n /**\n * This method removes all listeners of an event, or of all events when the call gives no event.\n *\n * @param event Optional event name to clear listeners for\n */\n off<K extends keyof E>(event?: K): void {\n if (event !== undefined) {\n this.listeners.delete(event);\n } else {\n this.listeners.clear();\n }\n }\n\n /**\n * This method gives the number of listeners of an event.\n *\n * @param event The event name\n * @returns Number of registered listeners\n */\n listenerCount<K extends keyof E>(event: K): number {\n return this.listeners.get(event)?.size ?? 0;\n }\n\n /**\n * This method gives the names of the events that have one or more listeners.\n */\n eventNames(): (keyof E)[] {\n return Array.from(this.listeners.keys());\n }\n\n /**\n * This method gives true when an event has one or more listeners.\n */\n hasListeners<K extends keyof E>(event: K): boolean {\n return this.listenerCount(event) > 0;\n }\n\n /**\n * This method removes all listeners and releases the resources.\n */\n dispose(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * This function makes an event emitter for an event map.\n *\n * This is a convenience factory function.\n *\n * @example\n * const events = createEmitter<ListEvents<number>>()\n */\nexport const createEmitter = <E extends EventMap>(): Emitter<E> => {\n return new Emitter<E>();\n};\n\n/**\n * Event batching utility for reducing event noise.\n * This class collects events and emits them in batches.\n *\n * @example\n * const batcher = new EventBatcher(emitter, 'add', 100)\n * batcher.queue({ value: 1, index: 0 })\n * batcher.queue({ value: 2, index: 1 })\n * // After 100ms or flush(), emits single 'batch-add' event with both items\n */\nexport class EventBatcher<E extends EventMap, K extends keyof E> {\n private emitter: Emitter<E & { [P in `batch-${K & string}`]: E[K][] }>;\n private event: K;\n private delayMs: number;\n private batch: E[K][] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n emitter: Emitter<E & { [P in `batch-${K & string}`]: E[K][] }>,\n event: K,\n delayMs: number\n ) {\n this.emitter = emitter;\n this.event = event;\n this.delayMs = delayMs;\n }\n\n /**\n * This method adds an event to the current batch.\n */\n queue(payload: E[K]): void {\n this.batch.push(payload);\n\n if (this.timer === null) {\n this.timer = setTimeout(() => this.flush(), this.delayMs);\n }\n }\n\n /**\n * This method emits all batched events at once.\n */\n flush(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n if (this.batch.length > 0) {\n const batchEvent = `batch-${String(this.event)}` as keyof (E & { [P in `batch-${K & string}`]: E[K][] });\n this.emitter.emit(batchEvent, this.batch as any);\n this.batch = [];\n }\n }\n\n /**\n * This method sends the events of the batch and releases the resources.\n */\n dispose(): void {\n this.flush();\n }\n}\n\n/**\n * Async event emitter that gives promises.\n * This class waits for all async listeners to complete.\n *\n * @example\n * const emitter = new AsyncEmitter<{ save: { data: string } }>()\n *\n * emitter.on('save', async ({ data }) => {\n * await database.save(data)\n * })\n *\n * await emitter.emit('save', { data: 'test' }) // Waits for save\n */\nexport class AsyncEmitter<E extends EventMap> {\n private listeners = new Map<keyof E, Set<Listener<any>>>();\n\n on<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n listeners = new Set();\n this.listeners.set(event, listeners);\n }\n listeners.add(listener);\n\n return () => {\n listeners!.delete(listener);\n if (listeners!.size === 0) {\n this.listeners.delete(event);\n }\n };\n }\n\n /**\n * This method emits an event and waits until all async listeners complete.\n *\n * @param event The event name\n * @param payload The event payload\n * @returns Promise that resolves when all listeners complete\n */\n async emit<K extends keyof E>(event: K, payload: E[K]): Promise<void> {\n const listeners = this.listeners.get(event);\n if (listeners) {\n const promises = Array.from(listeners).map((listener) =>\n Promise.resolve().then(() => listener(payload))\n );\n await Promise.all(promises);\n }\n }\n\n off<K extends keyof E>(event?: K): void {\n if (event !== undefined) {\n this.listeners.delete(event);\n } else {\n this.listeners.clear();\n }\n }\n\n listenerCount<K extends keyof E>(event: K): number {\n return this.listeners.get(event)?.size ?? 0;\n }\n\n eventNames(): (keyof E)[] {\n return Array.from(this.listeners.keys());\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * Utility to forward events from one emitter to another.\n * Useful for composing event sources.\n *\n * @example\n * const child = new Emitter<ChildEvents>()\n * const parent = new Emitter<ParentEvents>()\n *\n * forwardEvent(child, parent, 'childEvent', 'parentEvent')\n */\nexport const forwardEvent = <\n E1 extends EventMap,\n E2 extends EventMap,\n K1 extends keyof E1,\n K2 extends keyof E2\n>(\n source: Emitter<E1>,\n target: Emitter<E2>,\n sourceEvent: K1,\n targetEvent: K2,\n transform?: (payload: E1[K1]) => E2[K2]\n): Unsubscribe => {\n return source.on(sourceEvent, (payload) => {\n const transformedPayload = transform\n ? transform(payload)\n : (payload as any);\n target.emit(targetEvent, transformedPayload);\n });\n};\n\n/**\n * This function makes a filtered event subscription that fires only when the predicate is true.\n *\n * @example\n * const emitter = new Emitter<{ change: { value: number } }>()\n *\n * onWhen(emitter, 'change', ({ value }) => value > 10, ({ value }) => {\n * console.log('Value exceeded 10:', value)\n * })\n */\nexport const onWhen = <E extends EventMap, K extends keyof E>(\n emitter: Emitter<E>,\n event: K,\n predicate: (payload: E[K]) => boolean,\n listener: Listener<E[K]>\n): Unsubscribe => {\n return emitter.on(event, (payload) => {\n if (predicate(payload)) {\n listener(payload);\n }\n });\n};\n","/**\n * The removal channel of a stack of layers (C23).\n *\n * Some layers remove entries or elements by themselves. The bounded layers drop one when they are full.\n * `lruMap` evicts one, and `ttlMap` removes an expired one. A layer\n * above them does not call these removals, so it cannot see them. The removal channel tells it.\n *\n * - Each removing layer gives its channel under the key `removals`. Its channel gives its own removals and the\n * removals of the channel below it.\n * - A layer that does not remove forwards the channel below it: a proxy gives each unknown key of its target.\n * - `eventedMap` and the other evented layers emit an event for each removal of the channel below them.\n *\n * @example\n * const cache = compose(eventedMap<string, number>(), lruMap({ capacity: 2 }))(hashMap());\n * cache.on(\"delete\", ({ key, reason }) => console.log(key, reason)); // an eviction gives the reason \"evict\"\n */\n\nimport type { Listener, Unsubscribe } from \"./events.js\";\n\n/** The key of the removal channel on a layer. */\nexport const removals: unique symbol = Symbol.for(\"@mark1russell7/collections/removals\");\n\n/**\n * The cause of a removal: a bounded layer drops, `lruMap` evicts and `ttlMap` removes an expired entry.\n */\nexport type RemovalReason = \"drop\" | \"evict\" | \"expire\";\n\n/** A removal from a map: the key and the value that the layer removed. */\nexport interface MapRemoval<K, V> {\n readonly key: K;\n readonly value: V;\n readonly reason: RemovalReason;\n}\n\n/**\n * A removal of an element: the element and the end that it left. A removal from a collection with no ends,\n * for example by `ttlCollection`, has no `end`.\n */\nexport interface ElementRemoval<T> {\n readonly value: T;\n readonly end?: \"first\" | \"last\";\n readonly reason: RemovalReason;\n}\n\n/** A channel of removals. The listener gets each removal after the collection changed. */\nexport interface RemovalChannel<R> {\n on(listener: Listener<R>): Unsubscribe;\n}\n\n/** The channel of a removing layer, and the function that sends its own removals. */\nexport interface RemovalSource<R> {\n readonly channel: RemovalChannel<R>;\n emit(removal: R): void;\n}\n\n/**\n * This function gives the removal channel of a collection, or `undefined` when no layer of it removes.\n */\nexport function removalsOf<R>(collection: object): RemovalChannel<R> | undefined {\n const channel: unknown = (collection as { readonly [removals]?: unknown })[removals];\n if (typeof channel !== \"object\" || channel === null) return undefined;\n return typeof (channel as { on?: unknown }).on === \"function\" ? (channel as RemovalChannel<R>) : undefined;\n}\n\n/**\n * This function makes the channel of a removing layer over `next`.\n * The channel forwards each removal below. It calls `below` first, so the layer corrects its own state first.\n */\nexport function removalSource<R>(next: object, below?: (removal: R) => void): RemovalSource<R> {\n const listeners = new Set<Listener<R>>();\n const emit = (removal: R): void => {\n for (const listener of [...listeners]) listener(removal);\n };\n removalsOf<R>(next)?.on((removal) => {\n below?.(removal);\n emit(removal);\n });\n const channel: RemovalChannel<R> = {\n on(listener) {\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n };\n return { channel, emit };\n}\n","/**\n * A set of listeners for the events of a storage: the change batches of `observe()`, or the status\n * of a sync. A storage package uses it, so each storage treats its listeners in the same way.\n */\n\n/** The function that gets the error of a listener. */\nexport type ListenerErrorHandler = (error: unknown) => void;\n\n/**\n * The default handler of the error of a listener. It throws the error again in a microtask, as an\n * `EventTarget` reports the error of a listener. Thus the error is not lost, and the write that\n * sent the event does not fail.\n */\nexport const reportListenerError: ListenerErrorHandler = (error) => {\n queueMicrotask(() => {\n throw error;\n });\n};\n\n/**\n * The listeners of one kind of event.\n *\n * - `emit()` gives the event to each listener, in the order of `add()`.\n * - A listener that `add()` gets during an `emit()` gets the next event, not this one.\n * - The error of a listener goes to the error handler. The other listeners get the event.\n * - The same function can be added two times. Each `add()` gives its own function that removes it.\n */\nexport class StorageListeners<E> {\n private readonly listeners = new Set<{ readonly listener: (event: E) => void }>();\n private readonly onError: ListenerErrorHandler;\n\n /** @param onError - The function that gets the error of a listener. The default is `reportListenerError`. */\n constructor(onError: ListenerErrorHandler = reportListenerError) {\n this.onError = onError;\n }\n\n /** The number of listeners. */\n get size(): number {\n return this.listeners.size;\n }\n\n /**\n * This method adds a listener.\n *\n * @returns The function that removes the listener. A second use of it does nothing.\n */\n add(listener: (event: E) => void): () => void {\n const entry = { listener };\n this.listeners.add(entry);\n return () => {\n this.listeners.delete(entry);\n };\n }\n\n /** This method gives the event to each listener. */\n emit(event: E): void {\n for (const entry of [...this.listeners]) {\n // A listener that a listener before it removed gets no event\n if (!this.listeners.has(entry)) continue;\n try {\n entry.listener(event);\n } catch (error) {\n this.onError(error);\n }\n }\n }\n\n /** This method removes each listener. */\n clear(): void {\n this.listeners.clear();\n }\n}\n","/**\n * The keys of an ordered list: fractional indexing with base-62 keys. A\n * key is a string. Each item of the list keeps one, and the list sorts by it. An item that moves\n * between two others gets a key between theirs, so a move writes one item and no other.\n *\n * - A key has an integer part and a fraction part. The first character of the integer part gives its\n * length. An insertion at an end changes the integer part, so the keys stay short.\n * - An insertion between two keys uses the fraction part, which can grow without a limit. Thus the keys\n * do not run out, and the list needs no rebalance.\n * - Compare two keys by the code units of the strings (`a < b`), not with `localeCompare`.\n * - Two writers that move items into the same gap at the same time can get the same key. Sort by the\n * key, then by the id of the item, so each reader sees one order.\n *\n * The algorithm is the one of the `fractional-indexing` package of Rocicorp (CC0), after the article\n * \"Implementing Fractional Indexing\" of David Greenspan.\n */\n\n/** The digits of a key, in ascending order of their code units. */\nexport const KEY_DIGITS = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nconst ZERO = KEY_DIGITS[0]!;\nconst LAST = KEY_DIGITS[KEY_DIGITS.length - 1]!;\n/** The smallest integer part. No key comes before it. */\nconst SMALLEST_INTEGER = `A${ZERO.repeat(26)}`;\n\nfunction invalid(message: string): RangeError {\n return new RangeError(message);\n}\n\n/** This function gives the length of an integer part from its head character: a to z and Z to A give 2 to 27. */\nfunction integerLength(head: string): number {\n if (head >= \"a\" && head <= \"z\") return head.charCodeAt(0) - \"a\".charCodeAt(0) + 2;\n if (head >= \"A\" && head <= \"Z\") return \"Z\".charCodeAt(0) - head.charCodeAt(0) + 2;\n throw invalid(`A key cannot start with \"${head}\"`);\n}\n\nfunction integerPart(key: string): string {\n const length = integerLength(key[0] ?? \"\");\n if (length > key.length) throw invalid(`The key \"${key}\" is too short for its integer part`);\n return key.slice(0, length);\n}\n\nfunction validateKey(key: string): void {\n if (typeof key !== \"string\" || key === \"\") throw invalid(\"A key is a string that is not empty\");\n for (const c of key) if (!KEY_DIGITS.includes(c)) throw invalid(`The key \"${key}\" has a character that is no digit of a key`);\n if (key === SMALLEST_INTEGER) throw invalid(`The key \"${key}\" is reserved`);\n const fraction = key.slice(integerPart(key).length);\n if (fraction.endsWith(ZERO)) throw invalid(`The fraction part of the key \"${key}\" ends with ${ZERO}`);\n}\n\n/** A fraction strictly between two fractions. `b` null is the end. Neither one ends with the zero digit. */\nfunction midpoint(a: string, b: string | null): string {\n if (b !== null) {\n let n = 0;\n while ((a[n] ?? ZERO) === b[n]) n++;\n if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));\n }\n const digitA = a ? KEY_DIGITS.indexOf(a[0]!) : 0;\n const digitB = b !== null ? KEY_DIGITS.indexOf(b[0]!) : KEY_DIGITS.length;\n if (digitB - digitA > 1) return KEY_DIGITS[Math.round((digitA + digitB) / 2)]!;\n // The first digits are next to each other\n if (b !== null && b.length > 1) return b.slice(0, 1);\n return KEY_DIGITS[digitA]! + midpoint(a.slice(1), null);\n}\n\nfunction incrementInteger(x: string): string | null {\n const [head, ...digits] = x.split(\"\") as [string, ...string[]];\n let carry = true;\n for (let i = digits.length - 1; carry && i >= 0; i--) {\n const d = KEY_DIGITS.indexOf(digits[i]!) + 1;\n if (d === KEY_DIGITS.length) digits[i] = ZERO;\n else {\n digits[i] = KEY_DIGITS[d]!;\n carry = false;\n }\n }\n if (!carry) return head + digits.join(\"\");\n if (head === \"Z\") return `a${ZERO}`;\n if (head === \"z\") return null;\n const next = String.fromCharCode(head.charCodeAt(0) + 1);\n if (next > \"a\") digits.push(ZERO);\n else digits.pop();\n return next + digits.join(\"\");\n}\n\nfunction decrementInteger(x: string): string | null {\n const [head, ...digits] = x.split(\"\") as [string, ...string[]];\n let borrow = true;\n for (let i = digits.length - 1; borrow && i >= 0; i--) {\n const d = KEY_DIGITS.indexOf(digits[i]!) - 1;\n if (d === -1) digits[i] = LAST;\n else {\n digits[i] = KEY_DIGITS[d]!;\n borrow = false;\n }\n }\n if (!borrow) return head + digits.join(\"\");\n if (head === \"a\") return `Z${LAST}`;\n if (head === \"A\") return null;\n const next = String.fromCharCode(head.charCodeAt(0) - 1);\n if (next < \"Z\") digits.push(LAST);\n else digits.pop();\n return next + digits.join(\"\");\n}\n\n/**\n * This function gives a key strictly between two keys. Without `prev`, the key comes before `next`.\n * Without `next`, it comes after `prev`. Without both, it gives the first key of a list (\"a0\").\n *\n * @throws RangeError when a key is not valid, or when `prev` is not before `next`\n *\n * @example\n * ```ts\n * keyBetween(undefined, undefined); // \"a0\"\n * keyBetween(\"a0\", undefined); // \"a1\", after a0\n * keyBetween(\"a0\", \"a1\"); // \"a0V\"\n * ```\n */\nexport function keyBetween(prev: string | null | undefined, next: string | null | undefined): string {\n const a = prev ?? null;\n const b = next ?? null;\n if (a !== null) validateKey(a);\n if (b !== null) validateKey(b);\n if (a !== null && b !== null && a >= b) throw invalid(`The key \"${a}\" is not before the key \"${b}\"`);\n if (a === null) {\n if (b === null) return `a${ZERO}`;\n const ib = integerPart(b);\n const fb = b.slice(ib.length);\n if (ib === SMALLEST_INTEGER) return ib + midpoint(\"\", fb);\n if (ib < b) return ib;\n const decremented = decrementInteger(ib);\n if (decremented === null) throw invalid(\"No key comes before this one\");\n return decremented;\n }\n const ia = integerPart(a);\n const fa = a.slice(ia.length);\n if (b === null) {\n const incremented = incrementInteger(ia);\n return incremented === null ? ia + midpoint(fa, null) : incremented;\n }\n const ib = integerPart(b);\n const fb = b.slice(ib.length);\n if (ia === ib) return ia + midpoint(fa, fb);\n const incremented = incrementInteger(ia);\n if (incremented === null) throw invalid(\"No key comes after this one\");\n if (incremented < b) return incremented;\n return ia + midpoint(fa, null);\n}\n\n/**\n * This function gives `count` keys in ascending order, strictly between two keys.\n * Use it to put several items at one place, or to give keys to a new list.\n *\n * @throws RangeError as `keyBetween`, or when `count` is not an integer of 0 or more\n */\nexport function keysBetween(prev: string | null | undefined, next: string | null | undefined, count: number): string[] {\n if (!Number.isInteger(count) || count < 0) throw invalid(`A count of keys is an integer of 0 or more, not ${count}`);\n const a = prev ?? null;\n const b = next ?? null;\n if (count === 0) return [];\n if (count === 1) return [keyBetween(a, b)];\n if (b === null) {\n const keys = [keyBetween(a, null)];\n for (let i = 1; i < count; i++) keys.push(keyBetween(keys[i - 1]!, null));\n return keys;\n }\n if (a === null) {\n const keys = [keyBetween(null, b)];\n for (let i = 1; i < count; i++) keys.push(keyBetween(null, keys[i - 1]!));\n return keys.reverse();\n }\n const half = Math.floor(count / 2);\n const middle = keyBetween(a, b);\n return [...keysBetween(a, middle, half), middle, ...keysBetween(middle, b, count - half - 1)];\n}\n\n/** The options of `isValidKey`. */\nexport interface KeyCheckOptions {\n /** The longest key that the check accepts. The default is 1024 characters. */\n readonly maxLength?: number;\n}\n\n/**\n * This function tells if a value is a valid key, for example a key that a client writes. A key that\n * is longer than `maxLength` is not valid.\n */\nexport function isValidKey(key: unknown, options: KeyCheckOptions = {}): key is string {\n if (typeof key !== \"string\" || key.length > (options.maxLength ?? 1024)) return false;\n try {\n validateKey(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/** An item of an ordered list: its id and its key. */\nexport interface KeyedItem {\n readonly id: string;\n readonly key: string;\n}\n\n/**\n * This function gives the writes of a move: the new key of the item that moves, and new keys for the\n * neighbors that need them. Give the other items of the list in order (by key, then by id), without\n * the item that moves. Also give the index of the drop, from 0 to their number (`dropIndex`).\n *\n * Two writers can give two items one key. A drop between two such items has no key between them.\n * So the helper first gives new keys to the items after the drop that have the key of the item before\n * it. Each write is `{ id, key }`. The writes of the neighbors come first, and the write of the item\n * that moves comes last.\n *\n * @throws RangeError when the index is outside the list, when the list holds the item that moves, or\n * when a key is not valid\n *\n * @example\n * ```ts\n * const index = dropIndex(pointer, others.map(centerOf));\n * for (const { id, key } of keysForDrop(others, index, dragged.id)) await save(id, { rank: key });\n * ```\n */\nexport function keysForDrop(items: readonly KeyedItem[], index: number, movingId: string): Array<{ id: string; key: string }> {\n if (!Number.isInteger(index) || index < 0 || index > items.length) throw invalid(`The index ${index} is outside the list of ${items.length} items`);\n if (items.some((item) => item.id === movingId)) throw invalid(`The list holds the item that moves (${movingId})`);\n const prev = items[index - 1]?.key ?? null;\n // The items from the index on that do not come after the item before the drop need new keys\n let end = index;\n while (end < items.length && prev !== null && items[end]!.key <= prev) end++;\n const writes: Array<{ id: string; key: string }> = [];\n if (end > index) {\n const keys = keysBetween(prev, items[end]?.key ?? null, end - index);\n for (let i = index; i < end; i++) writes.push({ id: items[i]!.id, key: keys[i - index]! });\n }\n const next = writes.length > 0 ? writes[0]!.key : (items[index]?.key ?? null);\n writes.push({ id: movingId, key: keyBetween(prev, next) });\n return writes;\n}\n\n/** The order of two keys: the code units of the strings, as the keys need (not `localeCompare`). */\nexport function compareKeys(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** A point, for example the center of an item on the screen. */\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * This function gives the index at which a point goes among the items of a list on the screen.\n * The reading order is the rows from top to bottom, and each row from left to right.\n * The index is that of the first item whose center comes after the point, from 0 to the number of items. A center within\n * `rowTolerance` of the point on the vertical axis is in the row of the point.\n *\n * Give the centers in reading order, the same order as the keys, and without the item that moves.\n *\n * @example\n * ```ts\n * const index = dropIndex(pointer, others.map(centerOf));\n * const key = keyBetween(keys[index - 1], keys[index]);\n * ```\n */\nexport function dropIndex(point: Point, centers: readonly Point[], rowTolerance = 24): number {\n for (let i = 0; i < centers.length; i++) {\n const c = centers[i]!;\n if (point.y < c.y - rowTolerance) return i;\n if (Math.abs(point.y - c.y) <= rowTolerance && point.x < c.x) return i;\n }\n return centers.length;\n}\n","/**\n * Default implementations of equality, hashing, and comparison functions.\n *\n * This module gives sensible defaults for primitive types and utilities for\n * making custom comparators.\n */\n\nimport type { Eq, Hash, Compare } from \"../core/traits.js\";\n\n// ============================================================================\n// Default Equality\n// ============================================================================\n\n/**\n * Default equality using strict equality (===).\n * Works for primitives and reference equality for objects.\n */\nexport const defaultEq: Eq<any> = (a, b) => a === b;\n\n/**\n * Structural equality for objects (shallow comparison of properties).\n * This function compares own enumerable properties using ===.\n */\nexport const shallowEq: Eq<any> = (a, b) => {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n if (a === null || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) return false;\n if (a[key] !== b[key]) return false;\n }\n\n return true;\n};\n\n/** SameValueZero: the meaning of `===`, and NaN equals NaN. */\nconst sameValueZero = (a: unknown, b: unknown): boolean => a === b || (Number.isNaN(a) && Number.isNaN(b));\n\nconst isObject = (value: unknown): value is object => typeof value === \"object\" && value !== null;\n\n/** The pairs that one comparison holds equal. The log lets a failed try remove its pairs. */\ninterface HeldPairs {\n readonly partners: Map<object, Set<object>>;\n readonly log: [object, object][];\n}\n\nfunction releasePairs(held: HeldPairs, mark: number): void {\n while (held.log.length > mark) {\n const [a, b] = held.log.pop()!;\n held.partners.get(a)?.delete(b);\n }\n}\n\nfunction equalElements(a: ArrayLike<unknown>, b: ArrayLike<unknown>): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!sameValueZero(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The kinds of `equalObjects` and `hashFields`, so that the relation and its hash stay in step. */\nconst isBinary = (value: object): value is ArrayBufferLike | DataView =>\n value instanceof DataView || value instanceof ArrayBuffer || (typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer);\n\nconst isOpaque = (value: object): boolean => value instanceof Promise || value instanceof WeakMap || value instanceof WeakSet || value instanceof WeakRef;\n\nconst isBoxed = (value: object): boolean =>\n value instanceof Number || value instanceof String || value instanceof Boolean || value instanceof BigInt || value instanceof Symbol;\n\nfunction bytesOf(value: ArrayBufferLike | DataView): Uint8Array {\n return ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value);\n}\n\nfunction enumerableKeys(value: object): (string | symbol)[] {\n return Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));\n}\n\nfunction equalKeys(a: any, b: any, held: HeldPairs): boolean {\n const keys = enumerableKeys(a);\n if (keys.length !== enumerableKeys(b).length) return false;\n return keys.every((key) => Object.prototype.propertyIsEnumerable.call(b, key) && equalValues(a[key], b[key], held));\n}\n\n/**\n * The comparison of the entries of two maps, or of the members of two sets. A primitive key finds\n * its partner by `has`. An object key tries each object key of `b` that is not taken yet. The first\n * partner is correct, because the relation is an equivalence.\n */\nfunction equalEntries(a: Map<unknown, unknown> | Set<unknown>, b: Map<unknown, unknown> | Set<unknown>, held: HeldPairs): boolean {\n if (a.size !== b.size) return false;\n const valueAt = (key: unknown): unknown => (b instanceof Map ? b.get(key) : key);\n const free = [...b.entries()].filter(([key]) => isObject(key));\n for (const [key, value] of a.entries()) {\n if (!isObject(key)) {\n if (!b.has(key) || !equalValues(value, valueAt(key), held)) return false;\n continue;\n }\n const at = free.findIndex(([otherKey, otherValue]) => {\n const mark = held.log.length;\n if (equalValues(key, otherKey, held) && equalValues(value, otherValue, held)) return true;\n releasePairs(held, mark);\n return false;\n });\n if (at < 0) return false;\n free.splice(at, 1);\n }\n return true;\n}\n\n/** The comparison of two objects with the same prototype. */\nfunction equalObjects(a: any, b: any, held: HeldPairs): boolean {\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!equalValues(a[i], b[i], held)) return false;\n }\n return true;\n }\n if (isBinary(a)) return equalElements(bytesOf(a), bytesOf(b));\n if (ArrayBuffer.isView(a)) return equalElements(a as unknown as ArrayLike<unknown>, b);\n if (isOpaque(a)) return false;\n if (a instanceof Date && !sameValueZero(a.getTime(), b.getTime())) return false;\n if (a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags)) return false;\n if (a instanceof Error && !(a.name === b.name && a.message === b.message && equalValues(a.cause, b.cause, held))) return false;\n if (isBoxed(a) && !sameValueZero(a.valueOf(), b.valueOf())) return false;\n if ((a instanceof Map || a instanceof Set) && !equalEntries(a, b, held)) return false;\n return equalKeys(a, b, held);\n}\n\n/**\n * The comparison of two values. A pair stays held after it passes, so a shared or cyclic part\n * costs one visit. A failure ends the whole comparison, or the try in `equalEntries`, which\n * releases its pairs.\n */\nfunction equalValues(a: unknown, b: unknown, held: HeldPairs): boolean {\n if (sameValueZero(a, b)) return true;\n if (!isObject(a) || !isObject(b)) return false;\n if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;\n let partners = held.partners.get(a);\n if (partners?.has(b)) return true;\n if (partners === undefined) {\n partners = new Set();\n held.partners.set(a, partners);\n }\n partners.add(b);\n held.log.push([a, b]);\n return equalObjects(a, b, held);\n}\n\n/**\n * Deep structural equality. This relation is an equivalence: it is reflexive, symmetric and\n * transitive, for each value.\n *\n * - Primitives compare by SameValueZero: NaN equals NaN, and 0 equals -0.\n * - Two objects must have the same prototype. So `{}` differs from `Object.create(null)`, from an\n * instance of a class with the same keys, and from an object of another realm.\n * - Arrays compare by length and by index. A hole equals `undefined`.\n * - Typed arrays compare by element. `ArrayBuffer`, `SharedArrayBuffer` and `DataView` compare by byte.\n * - `Date` compares by time, `RegExp` by source and flags, and `Error` by name, message and cause.\n * - A boxed primitive compares by its value. `Map` and `Set` compare by entries, in any order. An object key\n * matches a deep-equal key.\n * - Each other object compares by its own enumerable keys, strings and symbols, in any order. The objects above do too,\n * except arrays and binary data.\n * - Functions, `Promise`, `WeakMap`, `WeakSet` and `WeakRef` compare by identity.\n * - Cycles are safe: two cyclic values are equal when they unfold to the same infinite tree.\n *\n * The recursion follows the depth of the data, so a very deep value can exhaust the stack.\n * `defaultHash` agrees with this relation: two equal values have one hash.\n */\nexport const deepEq: Eq<any> = (a, b): boolean => equalValues(a, b, { partners: new Map(), log: [] });\n\n/**\n * Equality by comparing a specific property.\n *\n * @example\n * const userEq = eqBy<User, 'id'>('id')\n * // or with accessor function:\n * const userEq = eqBy<User>((u) => u.id)\n */\nexport const eqBy = <T, K extends keyof T = keyof T>(\n keyOrFn: K | ((value: T) => any)\n): Eq<T> => {\n const accessor = typeof keyOrFn === \"function\" ? keyOrFn : (v: T) => v[keyOrFn];\n return (a, b) => accessor(a) === accessor(b);\n};\n\n// ============================================================================\n// Default Hashing\n// ============================================================================\n\n/** The hash of one primitive or function. */\nfunction hashPrimitive(value: unknown): number {\n if (value === null) return 0;\n if (value === undefined) return 1;\n switch (typeof value) {\n case \"boolean\":\n return value ? 1 : 0;\n case \"number\":\n return hashNumber(value);\n case \"string\":\n return hashString(value);\n case \"symbol\":\n return hashString(value.toString());\n case \"bigint\":\n return hashString(value.toString());\n default:\n return 2;\n }\n}\n\n/** The levels of an object that `defaultHash` reads. A cyclic value unfolds to this depth and stops. */\nconst HASH_DEPTH = 16;\n\n/** The hashes of one call, by object and by remaining depth. A shared part costs one visit per depth. */\ntype HashMemo = Map<object, number[]>;\n\n/** This function adds one hash to a running hash. The result depends on the order. */\nconst mix = (hash: number, part: number): number => (Math.imul(hash, 31) + part) | 0;\n\n/** The finalizer of MurmurHash3. It makes a sum of entries depend on each pair, not on each half. */\nfunction scramble(hash: number): number {\n let mixed = hash ^ (hash >>> 16);\n mixed = Math.imul(mixed, 0x85ebca6b);\n mixed ^= mixed >>> 13;\n mixed = Math.imul(mixed, 0xc2b2ae35);\n return mixed ^ (mixed >>> 16);\n}\n\n/** The start values of the kinds. Two kinds do not compare equal, so their hashes can differ. */\nconst KIND = { array: 3, binary: 5, elements: 7, opaque: 11, record: 13 } as const;\n\nconst hashAt = (value: unknown, depth: number, memo: HashMemo): number =>\n isObject(value) ? hashObject(value, depth, memo) : hashPrimitive(value);\n\nfunction hashElements(start: number, elements: ArrayLike<unknown>): number {\n let hash = start;\n for (let i = 0; i < elements.length; i++) hash = mix(hash, hashPrimitive(elements[i]));\n return hash;\n}\n\n/** The sum of the entries of a map or a set. A sum does not depend on the order of the entries. */\nfunction hashEntries(value: Map<unknown, unknown> | Set<unknown>, depth: number, memo: HashMemo): number {\n let sum = 0;\n for (const [key, entry] of value.entries()) sum = (sum + scramble(mix(hashAt(key, depth, memo), hashAt(entry, depth, memo)))) | 0;\n return sum;\n}\n\n/** The sum of the own enumerable keys and their values, as `equalKeys` reads them. */\nfunction hashKeys(value: any, depth: number, memo: HashMemo): number {\n let sum = 0;\n for (const key of enumerableKeys(value)) sum = (sum + scramble(mix(hashPrimitive(key), hashAt(value[key], depth, memo)))) | 0;\n return sum;\n}\n\n/** The hash of the fields of one object. This function reads only what `equalObjects` reads. */\nfunction hashFields(value: any, depth: number, memo: HashMemo): number {\n if (Array.isArray(value)) {\n let hash: number = KIND.array;\n for (let i = 0; i < value.length; i++) hash = mix(hash, hashAt(value[i], depth, memo));\n return hash;\n }\n if (isBinary(value)) return hashElements(KIND.binary, bytesOf(value));\n if (ArrayBuffer.isView(value)) return hashElements(KIND.elements, value as unknown as ArrayLike<unknown>);\n if (isOpaque(value)) return KIND.opaque;\n let hash: number = KIND.record;\n if (value instanceof Date) hash = mix(hash, hashNumber(value.getTime()));\n if (value instanceof RegExp) hash = mix(mix(hash, hashString(value.source)), hashString(value.flags));\n if (value instanceof Error) {\n hash = mix(mix(mix(hash, hashAt(value.name, depth, memo)), hashAt(value.message, depth, memo)), hashAt(value.cause, depth, memo));\n }\n if (isBoxed(value)) hash = mix(hash, hashPrimitive(value.valueOf()));\n if (value instanceof Map || value instanceof Set) hash = mix(hash, hashEntries(value, depth, memo));\n return mix(hash, hashKeys(value, depth, memo));\n}\n\n/** The hash of one object at one depth. The depth falls with each level, so a cycle ends. */\nfunction hashObject(value: object, depth: number, memo: HashMemo): number {\n if (depth === 0) return 0;\n let byDepth = memo.get(value);\n if (byDepth === undefined) {\n byDepth = [];\n memo.set(value, byDepth);\n }\n const known = byDepth[depth];\n if (known !== undefined) return known;\n const hash = hashFields(value, depth - 1, memo);\n byDepth[depth] = hash;\n return hash;\n}\n\n/**\n * This function is the default hash of a key. It agrees with `deepEq`: when `deepEq(a, b)` is true,\n * `defaultHash(a)` equals `defaultHash(b)`. So a hash map with `deepEq` finds an equal key.\n *\n * - The hash of an object reads the same fields as `deepEq`. The order of the keys of an object,\n * and of the entries of a `Map` or a `Set`, has no effect.\n * - The hash reads 16 levels, so a cyclic or very deep value ends. Two values that differ only\n * below that depth have one hash, and `deepEq` then tells them apart.\n * - A shared part costs one visit per level, so a dense graph ends.\n * - The hash of an object can change in a new version. Do not store it.\n */\nexport const defaultHash: Hash<any> = (value: any): number =>\n isObject(value) ? hashObject(value, HASH_DEPTH, new Map()) : hashPrimitive(value);\n\n/**\n * Hash function for strings using djb2 algorithm.\n */\nexport const hashString = (str: string): number => {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) + str.charCodeAt(i); // hash * 33 + c\n hash = hash & hash; // Convert to 32-bit integer\n }\n return hash >>> 0; // Convert to unsigned\n};\n\n/**\n * Hash function for numbers.\n */\nexport const hashNumber = (num: number): number => {\n if (Number.isNaN(num)) return 0;\n if (!Number.isFinite(num)) return num > 0 ? 1 : -1;\n\n // For integers, use the number itself\n if (Number.isInteger(num)) {\n return num | 0; // Convert to 32-bit int\n }\n\n // For floats, hash the string representation\n return hashString(num.toString());\n};\n\n/**\n * This function combines hash values into one hash.\n * Useful for hashing objects with multiple fields.\n *\n * @example\n * const pointHash: Hash<Point> = (p) =>\n * combineHashes(hashNumber(p.x), hashNumber(p.y))\n */\nexport const combineHashes = (...hashes: number[]): number => {\n let combined = 0;\n for (const hash of hashes) {\n combined = ((combined << 5) - combined) + hash;\n combined = combined & combined; // Convert to 32-bit int\n }\n return combined >>> 0; // Convert to unsigned\n};\n\n/**\n * This function makes a hash function that hashes by a property.\n *\n * @example\n * const userHash = hashBy<User>((u) => u.id)\n */\nexport const hashBy = <T>(accessor: (value: T) => any): Hash<T> => {\n return (value) => defaultHash(accessor(value));\n};\n\n// ============================================================================\n// Default Comparison\n// ============================================================================\n\n/** This function gives the place of `null` and `undefined` in the order of `defaultCompare`: `null`, then `undefined`, then each other value. */\nconst nullishRank = (value: unknown): number => (value === null ? 0 : value === undefined ? 1 : 2);\n\n/**\n * This comparator gives the natural order of primitives.\n * - `null` comes first, then `undefined`, then each other value.\n * - Numbers and dates compare as `numberCompare` and `dateCompare` compare them.\n * - Strings compare by `localeCompare`, and `false` comes before `true`.\n * - Two values of different types compare by their text, with `String`.\n */\nexport const defaultCompare: Compare<any> = (a, b) => {\n if (a === b) return 0;\n const nullish = nullishRank(a) - nullishRank(b);\n if (nullish !== 0) return nullish;\n\n // Handle dates\n if (a instanceof Date && b instanceof Date) {\n return dateCompare(a, b);\n }\n\n // Handle numbers\n if (typeof a === \"number\" && typeof b === \"number\") {\n return numberCompare(a, b);\n }\n\n // Handle strings\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a.localeCompare(b);\n }\n\n // Handle booleans\n if (typeof a === \"boolean\" && typeof b === \"boolean\") {\n return a === b ? 0 : a ? 1 : -1;\n }\n\n // Fallback: convert to string and compare\n return String(a).localeCompare(String(b));\n};\n\n/**\n * This comparator gives the order of numbers by value. It gives -1, 0 or 1.\n * - `NaN` comes first, and two `NaN` values give 0.\n * - Two equal infinities give 0, and 0 equals -0.\n */\nexport const numberCompare: Compare<number> = (a, b) => {\n if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : -1;\n if (Number.isNaN(b)) return 1;\n return a < b ? -1 : a > b ? 1 : 0;\n};\n\n/**\n * String comparison using locale-aware sorting.\n */\nexport const stringCompare: Compare<string> = (a, b) => a.localeCompare(b);\n\n/**\n * Case-insensitive string comparison.\n */\nexport const stringCompareIgnoreCase: Compare<string> = (a, b) =>\n a.toLowerCase().localeCompare(b.toLowerCase());\n\n/**\n * This comparator gives the order of dates by time, with `numberCompare`. An invalid date has the time `NaN`, so it comes\n * first, and two invalid dates give 0.\n */\nexport const dateCompare: Compare<Date> = (a, b) => numberCompare(a.getTime(), b.getTime());\n\n/**\n * Boolean comparison (false < true).\n */\nexport const booleanCompare: Compare<boolean> = (a, b) =>\n a === b ? 0 : a ? 1 : -1;\n\n// ============================================================================\n// Comparator Combinators\n// ============================================================================\n\n/**\n * This function reverses a comparator.\n *\n * @example\n * const descending = reversed(numberCompare)\n */\nexport const reversed = <T>(compare: Compare<T>): Compare<T> =>\n (a, b) => compare(b, a);\n\n/**\n * This function makes a comparator that compares by a specific property or function.\n *\n * @example\n * const byAge = comparing<Person>((p) => p.age)\n * const byName = comparing<Person, 'name'>('name')\n */\nexport const comparing = <T, K extends keyof T = keyof T>(\n keyOrFn: K | ((value: T) => any),\n compare: Compare<any> = defaultCompare\n): Compare<T> => {\n const accessor = typeof keyOrFn === \"function\" ? keyOrFn : (v: T) => v[keyOrFn];\n return (a, b) => compare(accessor(a), accessor(b));\n};\n\n/**\n * Chains comparators. If the first comparator gives 0 (equal),\n * tries the next comparator, and so on.\n *\n * @example\n * const userCompare = thenComparing(\n * comparing<User>('lastName'),\n * comparing<User>('firstName'),\n * comparing<User>('age')\n * )\n */\nexport const thenComparing = <T>(...comparators: Compare<T>[]): Compare<T> => {\n return (a, b) => {\n for (const compare of comparators) {\n const result = compare(a, b);\n if (result !== 0) return result;\n }\n return 0;\n };\n};\n\n/**\n * This function makes a comparator that treats null/undefined as less than all other values.\n *\n * @example\n * const compare = nullsFirst(numberCompare)\n */\nexport const nullsFirst = <T>(compare: Compare<T>): Compare<T | null | undefined> => {\n return (a, b) => {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n return compare(a, b);\n };\n};\n\n/**\n * This function makes a comparator that treats null/undefined as greater than all other values.\n *\n * @example\n * const compare = nullsLast(numberCompare)\n */\nexport const nullsLast = <T>(compare: Compare<T>): Compare<T | null | undefined> => {\n return (a, b) => {\n if (a == null && b == null) return 0;\n if (a == null) return 1;\n if (b == null) return -1;\n return compare(a, b);\n };\n};\n\n/**\n * This function makes a comparator from a key extraction function.\n * Elements are compared by their extracted keys.\n *\n * @example\n * const byLength = comparingKey<string>((s) => s.length)\n */\nexport const comparingKey = <T, K>(\n keyExtractor: (value: T) => K,\n keyCompare: Compare<K> = defaultCompare\n): Compare<T> => {\n return (a, b) => keyCompare(keyExtractor(a), keyExtractor(b));\n};\n","/**\n * ArrayList implementation - A dynamic array-backed list.\n *\n * This module gives O(1) indexed access and amortized O(1) append.\n * Mirrors java.util.ArrayList.\n *\n * @example\n * const list = arrayList<number>()\n * list.add(1)\n * list.add(2)\n * list.add(3)\n * console.log(list.get(1)) // 2\n */\n\nimport type { List, RandomAccess } from \"../interfaces/list.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Options for making an ArrayList.\n */\nexport interface ArrayListOptions<T> {\n /**\n * Initial capacity of the underlying array.\n * @default 10\n */\n initialCapacity?: number;\n\n /**\n * Equality function for comparing elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n}\n\n/**\n * ArrayList<T> - Resizable array implementation of the List interface.\n *\n * This class gives fast random access (O(1)) and fast append (amortized O(1)).\n * Insertion and removal in the middle shift elements (O(n)).\n *\n * This is the most commonly used list implementation.\n */\nexport class ArrayList<T> implements List<T>, RandomAccess {\n private _array: T[];\n private _size: number;\n private readonly _eq: Eq<T>;\n\n readonly supportsRandomAccess = true as const;\n\n constructor(options: ArrayListOptions<T> = {}) {\n const { initialCapacity = 10, eq = defaultEq } = options;\n this._array = new Array(initialCapacity);\n this._size = 0;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size and capacity\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Current capacity of the underlying array.\n */\n get capacity(): number {\n return this._array.length;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Indexed access\n // ========================================================================\n\n get(index: number): T {\n this.checkIndex(index);\n return this._array[index]!;\n }\n\n set(index: number, element: T): T {\n this.checkIndex(index);\n const old = this._array[index]!;\n this._array[index] = element;\n return old!;\n }\n\n // ========================================================================\n // Search\n // ========================================================================\n\n contains(element: T): boolean {\n return this.indexOf(element) !== -1;\n }\n\n indexOf(element: T, fromIndex: number = 0): number {\n if (fromIndex < 0) fromIndex = 0;\n for (let i = fromIndex; i < this._size; i++) {\n if (this._eq(this._array[i]!, element)) {\n return i;\n }\n }\n return -1;\n }\n\n lastIndexOf(element: T, fromIndex?: number): number {\n const start =\n fromIndex !== undefined\n ? Math.min(fromIndex, this._size - 1)\n : this._size - 1;\n for (let i = start; i >= 0; i--) {\n if (this._eq(this._array[i]!, element)) {\n return i;\n }\n }\n return -1;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) return false;\n }\n return true;\n }\n\n // ========================================================================\n // Addition\n // ========================================================================\n\n add(element: T): boolean {\n this.ensureCapacity(this._size + 1);\n this._array[this._size++] = element;\n return true;\n }\n\n push(element: T): void {\n this.add(element);\n }\n\n unshift(element: T): void {\n this.insert(0, element);\n }\n\n insert(index: number, element: T): void {\n this.checkInsertIndex(index);\n this.ensureCapacity(this._size + 1);\n\n // Shift elements to the right\n for (let i = this._size; i > index; i--) {\n this._array[i] = this._array[i - 1]!;\n }\n\n this._array[index] = element;\n this._size++;\n }\n\n insertAll(index: number, other: Iterable<T>): boolean {\n this.checkInsertIndex(index);\n const elements = Array.isArray(other) ? other : Array.from(other);\n if (elements.length === 0) return false;\n\n this.ensureCapacity(this._size + elements.length);\n\n // Shift existing elements to the right\n for (let i = this._size - 1; i >= index; i--) {\n this._array[i + elements.length] = this._array[i]!;\n }\n\n // Insert new elements\n for (let i = 0; i < elements.length; i++) {\n this._array[index + i] = elements[i];\n }\n\n this._size += elements.length;\n return true;\n }\n\n addAll(other: Iterable<T>): boolean {\n const elements = Array.isArray(other) ? other : Array.from(other);\n if (elements.length === 0) return false;\n\n this.ensureCapacity(this._size + elements.length);\n\n for (const element of elements) {\n this._array[this._size++] = element;\n }\n\n return true;\n }\n\n // ========================================================================\n // Removal\n // ========================================================================\n\n remove(element: T): boolean {\n const index = this.indexOf(element);\n if (index === -1) return false;\n this.removeAt(index);\n return true;\n }\n\n removeAt(index: number): T {\n this.checkIndex(index);\n const old = this._array[index]!;\n\n // Shift elements to the left\n for (let i = index; i < this._size - 1; i++) {\n this._array[i] = this._array[i + 1]!;\n }\n\n this._size--;\n // Clear the last element to allow GC\n this._array[this._size] = undefined as any;\n\n return old;\n }\n\n pop(): T {\n if (this.isEmpty) {\n throw new Error(\"Cannot pop from empty list\");\n }\n return this.removeAt(this._size - 1);\n }\n\n shift(): T {\n if (this.isEmpty) {\n throw new Error(\"Cannot shift from empty list\");\n }\n return this.removeAt(0);\n }\n\n removeRange(fromIndex: number, toIndex: number): void {\n this.checkRange(fromIndex, toIndex);\n const numToRemove = toIndex - fromIndex;\n if (numToRemove === 0) return;\n\n // Shift elements to the left\n for (let i = toIndex; i < this._size; i++) {\n this._array[i - numToRemove] = this._array[i]!;\n }\n\n // Clear removed elements\n for (let i = this._size - numToRemove; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n\n this._size -= numToRemove;\n }\n\n removeAll(other: Iterable<T>): boolean {\n const toRemove = new Set<T>();\n for (const element of other) {\n toRemove.add(element);\n }\n\n let writeIndex = 0;\n let modified = false;\n\n for (let readIndex = 0; readIndex < this._size; readIndex++) {\n const element = this._array[readIndex]!;\n let shouldRemove = false;\n\n // Check if element matches any in toRemove using custom equality\n for (const removeElement of toRemove) {\n if (this._eq(element, removeElement)) {\n shouldRemove = true;\n modified = true;\n break;\n }\n }\n\n if (!shouldRemove) {\n this._array[writeIndex++] = element;\n }\n }\n\n // Clear remaining elements\n for (let i = writeIndex; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n\n this._size = writeIndex;\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = Array.from(other);\n let writeIndex = 0;\n let modified = false;\n\n for (let readIndex = 0; readIndex < this._size; readIndex++) {\n const element = this._array[readIndex]!;\n let shouldRetain = false;\n\n // Check if element matches any in toRetain using custom equality\n for (const retainElement of toRetain) {\n if (this._eq(element, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n\n if (shouldRetain) {\n this._array[writeIndex++] = element;\n } else {\n modified = true;\n }\n }\n\n // Clear remaining elements\n for (let i = writeIndex; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n\n this._size = writeIndex;\n return modified;\n }\n\n clear(): void {\n // Clear all elements to allow GC\n for (let i = 0; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n this._size = 0;\n }\n\n // ========================================================================\n // Ordering\n // ========================================================================\n\n sort(compare: Compare<T> = defaultCompare): void {\n // Sort only the used portion of the array\n const slice = this._array.slice(0, this._size);\n slice.sort(compare);\n for (let i = 0; i < this._size; i++) {\n this._array[i] = slice[i]!;\n }\n }\n\n reverse(): void {\n let left = 0;\n let right = this._size - 1;\n while (left < right) {\n const temp = this._array[left]!;\n this._array[left] = this._array[right]!;\n this._array[right] = temp;\n left++;\n right--;\n }\n }\n\n // ========================================================================\n // Views\n // ========================================================================\n\n first(): T {\n if (this.isEmpty) {\n throw new Error(\"List is empty\");\n }\n return this._array[0]!;\n }\n\n last(): T {\n if (this.isEmpty) {\n throw new Error(\"List is empty\");\n }\n return this._array[this._size - 1]!;\n }\n\n subList(fromIndex: number, toIndex: number): List<T> {\n this.checkRange(fromIndex, toIndex);\n // For now, return a copy. Later we can implement a view.\n const sub = new ArrayList<T>({ eq: this._eq });\n for (let i = fromIndex; i < toIndex; i++) {\n sub.add(this._array[i]!);\n }\n return sub;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n for (let i = 0; i < this._size; i++) {\n yield this._array[i]!;\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n for (let i = 0; i < this._size; i++) {\n action(this._array[i]!, i);\n }\n }\n\n toArray(): T[] {\n return this._array.slice(0, this._size);\n }\n\n // ========================================================================\n // Capacity management\n // ========================================================================\n\n /**\n * This method makes sure that the capacity is at least the specified minimum.\n */\n ensureCapacity(minCapacity: number): void {\n if (minCapacity <= this._array.length) return;\n\n // Grow by 1.5x or to minCapacity, whichever is larger\n const newCapacity = Math.max(\n minCapacity,\n Math.floor(this._array.length * 1.5) + 1\n );\n\n const newArray = new Array(newCapacity);\n for (let i = 0; i < this._size; i++) {\n newArray[i] = this._array[i];\n }\n this._array = newArray;\n }\n\n /**\n * This method trims the capacity to the current size to minimize memory usage.\n */\n trimToSize(): void {\n if (this._size < this._array.length) {\n this._array = this._array.slice(0, this._size);\n }\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n private checkIndex(index: number): void {\n if (index < 0 || index >= this._size) {\n throw new RangeError(\n `Index ${index} out of bounds for size ${this._size}`\n );\n }\n }\n\n private checkInsertIndex(index: number): void {\n if (index < 0 || index > this._size) {\n throw new RangeError(\n `Index ${index} out of bounds for insert (size ${this._size})`\n );\n }\n }\n\n private checkRange(fromIndex: number, toIndex: number): void {\n if (fromIndex < 0 || toIndex > this._size || fromIndex > toIndex) {\n throw new RangeError(\n `Invalid range [${fromIndex}, ${toIndex}) for size ${this._size}`\n );\n }\n }\n}\n\n/**\n * Factory function to make an ArrayList.\n *\n * @example\n * const list = arrayList<number>()\n * const listWithEq = arrayList<User>({ eq: (a, b) => a.id === b.id })\n * const listFromArray = arrayList([1, 2, 3])\n */\nexport function arrayList<T>(\n optionsOrElements?: ArrayListOptions<T> | Iterable<T>\n): ArrayList<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const list = new ArrayList<T>();\n list.addAll(optionsOrElements as Iterable<T>);\n return list;\n }\n\n const list = new ArrayList<T>(optionsOrElements as ArrayListOptions<T>);\n return list;\n}\n","/**\n * ArrayDeque implementation - A ring buffer backed double-ended queue.\n *\n * This module gives O(1) insertion and removal at both ends.\n * More efficient than ArrayList for queue/stack operations.\n * Mirrors java.util.ArrayDeque.\n *\n * @example\n * const deque = arrayDeque<number>()\n * deque.addFirst(1)\n * deque.addLast(2)\n * deque.removeFirst() // 1\n */\n\nimport type { Deque } from \"../interfaces/queue.js\";\nimport type { Eq } from \"../core/traits.js\";\nimport { defaultEq } from \"../utils/defaults.js\";\n\n/**\n * Options for making an ArrayDeque.\n */\nexport interface ArrayDequeOptions<T> {\n /**\n * Initial capacity of the underlying array.\n * This value must be a power of 2 for efficient modulo operations.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * Equality function for comparing elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n}\n\n/**\n * ArrayDeque<T> - Ring buffer implementation of Deque.\n *\n * This class uses a circular array to give O(1) operations at both ends.\n * The array grows automatically when full.\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class ArrayDeque<T> implements Deque<T> {\n private _elements: (T | undefined)[];\n private _head: number; // Index of first element\n private _tail: number; // Index where next element will be added\n private readonly _eq: Eq<T>;\n\n constructor(options: ArrayDequeOptions<T> = {}) {\n const { initialCapacity = 16, eq = defaultEq } = options;\n // Ensure capacity is a power of 2 for efficient modulo using bitwise AND\n const capacity = this.nextPowerOfTwo(Math.max(8, initialCapacity));\n this._elements = new Array(capacity);\n this._head = 0;\n this._tail = 0;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n // Handle wraparound: (tail - head) & mask\n return (this._tail - this._head) & (this._elements.length - 1);\n }\n\n get isEmpty(): boolean {\n return this._head === this._tail;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Front operations (head)\n // ========================================================================\n\n addFirst(element: T): void {\n this._head = (this._head - 1) & (this._elements.length - 1);\n this._elements[this._head] = element;\n if (this._head === this._tail) {\n this.grow();\n }\n }\n\n offerFirst(element: T): boolean {\n this.addFirst(element);\n return true;\n }\n\n removeFirst(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n return this.pollFirst()!;\n }\n\n pollFirst(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n const element = this._elements[this._head];\n this._elements[this._head] = undefined;\n this._head = (this._head + 1) & (this._elements.length - 1);\n return element;\n }\n\n peekFirst(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n return this._elements[this._head]!;\n }\n\n peekFirstOrUndefined(): T | undefined {\n return this.isEmpty ? undefined : this._elements[this._head];\n }\n\n // ========================================================================\n // Back operations (tail)\n // ========================================================================\n\n addLast(element: T): void {\n this._elements[this._tail] = element;\n this._tail = (this._tail + 1) & (this._elements.length - 1);\n if (this._tail === this._head) {\n this.grow();\n }\n }\n\n offerLast(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n removeLast(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n return this.pollLast()!;\n }\n\n pollLast(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n this._tail = (this._tail - 1) & (this._elements.length - 1);\n const element = this._elements[this._tail];\n this._elements[this._tail] = undefined;\n return element;\n }\n\n peekLast(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n const lastIndex = (this._tail - 1) & (this._elements.length - 1);\n return this._elements[lastIndex]!;\n }\n\n peekLastOrUndefined(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n const lastIndex = (this._tail - 1) & (this._elements.length - 1);\n return this._elements[lastIndex];\n }\n\n // ========================================================================\n // Stack operations (LIFO at the end, as on a JavaScript array)\n // ========================================================================\n\n // push and pop work at the end, and shift/unshift at the front, in every collection of this\n // package. Before, they worked at the front here (the Java Deque rule), so a LinkedList used\n // as a List reversed the pushed elements (ARCHITECTURE-PROPOSALS P8).\n push(element: T): void {\n this.addLast(element);\n }\n\n pop(): T {\n return this.removeLast();\n }\n\n // ========================================================================\n // Queue operations (FIFO - add last, remove first)\n // ========================================================================\n\n offer(element: T): boolean {\n return this.offerLast(element);\n }\n\n poll(): T {\n return this.removeFirst();\n }\n\n peek(): T {\n return this.peekFirst();\n }\n\n peekOrUndefined(): T | undefined {\n return this.peekFirstOrUndefined();\n }\n\n pollOrUndefined(): T | undefined {\n return this.pollFirst();\n }\n\n enqueue(element: T): boolean {\n return this.offer(element);\n }\n\n dequeue(): T {\n return this.poll();\n }\n\n // ========================================================================\n // Collection operations\n // ========================================================================\n\n add(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n this.addLast(element);\n modified = true;\n }\n return modified;\n }\n\n contains(element: T): boolean {\n for (const item of this) {\n if (this._eq(item, element)) {\n return true;\n }\n }\n return false;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n remove(element: T): boolean {\n // Linear search for the first occurrence\n const mask = this._elements.length - 1;\n const size = this.size;\n for (let offset = 0; offset < size; offset++) {\n if (this._eq(this._elements[(this._head + offset) & mask]!, element)) {\n this.removeAtOffset(offset);\n return true;\n }\n }\n return false;\n }\n\n /**\n * This method removes the element at a position from the head. The shorter side moves one place.\n * (Before, a bitwise expression chose the side, and it was not a valid test.)\n */\n private removeAtOffset(offset: number): void {\n const mask = this._elements.length - 1;\n const size = this.size;\n if (offset < size / 2) {\n // Move the elements before it one place toward the tail\n for (let i = offset; i > 0; i--) {\n this._elements[(this._head + i) & mask] = this._elements[(this._head + i - 1) & mask];\n }\n this._elements[this._head] = undefined;\n this._head = (this._head + 1) & mask;\n } else {\n // Move the elements after it one place toward the head\n for (let i = offset; i < size - 1; i++) {\n this._elements[(this._head + i) & mask] = this._elements[(this._head + i + 1) & mask];\n }\n this._tail = (this._tail - 1) & mask;\n this._elements[this._tail] = undefined;\n }\n }\n\n\n removeAll(other: Iterable<T>): boolean {\n const toRemove = new Set<T>();\n for (const element of other) {\n toRemove.add(element);\n }\n\n let modified = false;\n for (const element of toRemove) {\n while (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = new Set(other);\n const newDeque = new ArrayDeque<T>({ eq: this._eq });\n\n for (const element of this) {\n let shouldRetain = false;\n for (const retainElement of toRetain) {\n if (this._eq(element, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n if (shouldRetain) {\n newDeque.addLast(element);\n }\n }\n\n const modified = newDeque.size !== this.size;\n this._elements = newDeque._elements;\n this._head = newDeque._head;\n this._tail = newDeque._tail;\n\n return modified;\n }\n\n clear(): void {\n // Clear all elements for GC\n let index = this._head;\n while (index !== this._tail) {\n this._elements[index] = undefined;\n index = (index + 1) & (this._elements.length - 1);\n }\n this._head = 0;\n this._tail = 0;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n let index = this._head;\n while (index !== this._tail) {\n yield this._elements[index]!;\n index = (index + 1) & (this._elements.length - 1);\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let arrayIndex = this._head;\n let logicalIndex = 0;\n while (arrayIndex !== this._tail) {\n action(this._elements[arrayIndex]!, logicalIndex);\n arrayIndex = (arrayIndex + 1) & (this._elements.length - 1);\n logicalIndex++;\n }\n }\n\n toArray(): T[] {\n const result: T[] = [];\n for (const element of this) {\n result.push(element);\n }\n return result;\n }\n\n // ========================================================================\n // Capacity management\n // ========================================================================\n\n /**\n * This method doubles the capacity of the deque.\n */\n private grow(): void {\n const oldCapacity = this._elements.length;\n const newCapacity = oldCapacity << 1; // Double capacity\n\n if (newCapacity < 0) {\n throw new Error(\"Deque too large\");\n }\n\n const newElements = new Array(newCapacity);\n\n // Copy elements from head to end of old array\n const rightSize = oldCapacity - this._head;\n for (let i = 0; i < rightSize; i++) {\n newElements[i] = this._elements[this._head + i];\n }\n\n // Copy wrapped elements from start of old array\n const leftSize = this._head;\n for (let i = 0; i < leftSize; i++) {\n newElements[rightSize + i] = this._elements[i];\n }\n\n // grow() runs when the array is full: head === tail and every slot holds an element. Then\n // `size` computes 0, so the old `this._tail = size` lost every element (BUGS-2026-07 C8).\n this._elements = newElements;\n this._head = 0;\n this._tail = oldCapacity;\n }\n\n /**\n * This method gives the next power of 2 >= n.\n */\n private nextPowerOfTwo(n: number): number {\n if (n <= 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n return n + 1;\n }\n\n // ========================================================================\n // Inspection\n // ========================================================================\n\n /**\n * This value is the current capacity of the underlying array.\n */\n get capacity(): number {\n return this._elements.length;\n }\n\n /**\n * This method gives a string representation for debugging.\n */\n toString(): string {\n return `ArrayDeque[${this.toArray().join(\", \")}]`;\n }\n}\n\n/**\n * Factory function to make an ArrayDeque.\n *\n * @example\n * const deque = arrayDeque<number>()\n * const dequeFromArray = arrayDeque([1, 2, 3])\n * const dequeWithOptions = arrayDeque<string>({ initialCapacity: 32 })\n */\nexport function arrayDeque<T>(\n optionsOrElements?: ArrayDequeOptions<T> | Iterable<T>\n): ArrayDeque<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const deque = new ArrayDeque<T>();\n deque.addAll(optionsOrElements as Iterable<T>);\n return deque;\n }\n\n return new ArrayDeque<T>(optionsOrElements as ArrayDequeOptions<T>);\n}\n","/**\n * HashMap implementation - A hash table with custom equality and hashing.\n *\n * This module gives O(1) average case lookup, insertion, and deletion.\n * This module supports custom equality and hash functions for keys.\n * Mirrors java.util.HashMap.\n *\n * @example\n * const map = hashMap<string, number>()\n * map.set('one', 1)\n * map.set('two', 2)\n * console.log(map.get('one')) // 1\n *\n * // Custom equality for object keys\n * const userMap = hashMap<User, Data>({\n * keyEq: (a, b) => a.id === b.id,\n * keyHash: (u) => hashString(u.id)\n * })\n */\n\nimport type { MapLike, Entry } from \"../interfaces/map.js\";\nimport type { Eq, Hash } from \"../core/traits.js\";\nimport { defaultEq, defaultHash } from \"../utils/defaults.js\";\n\n/**\n * Internal entry node for hash buckets.\n */\ninterface Node<K, V> {\n key: K;\n value: V;\n hash: number;\n next: Node<K, V> | null;\n}\n\n/**\n * Options for making a HashMap.\n */\nexport interface HashMapOptions<K, V> {\n /**\n * Initial capacity (number of buckets).\n * This value must be a power of 2.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * This option is the load factor threshold for a resize, from 0 to 1.\n * When size > capacity * loadFactor, the map resizes.\n * @default 0.75\n */\n loadFactor?: number;\n\n /**\n * Equality function for keys.\n * @default defaultEq (===)\n */\n keyEq?: Eq<K>;\n\n /**\n * Hash function for keys.\n * @default defaultHash\n */\n keyHash?: Hash<K>;\n\n /**\n * Equality function for values (used in containsValue).\n * @default defaultEq (===)\n */\n valueEq?: Eq<V>;\n}\n\n/**\n * HashMap<K, V> - Hash table implementation with custom equality/hashing.\n *\n * This class uses separate chaining for collision resolution.\n * The map resizes when its load factor is more than the threshold.\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class HashMap<K, V> implements MapLike<K, V> {\n private _buckets: (Node<K, V> | null)[];\n private _size: number;\n private readonly _loadFactor: number;\n private readonly _keyEq: Eq<K>;\n private readonly _keyHash: Hash<K>;\n private readonly _valueEq: Eq<V>;\n private _threshold: number;\n /**\n * The count of structural changes (a key added or removed, a clear, a resize). An iterator\n * records it at its start and throws when it changes. Before, a resize during iteration made\n * the iterator skip or repeat entries (BUGS-2026-07 L15).\n */\n private _modCount = 0;\n\n constructor(options: HashMapOptions<K, V> = {}) {\n const {\n initialCapacity = 16,\n loadFactor = 0.75,\n keyEq = defaultEq,\n keyHash = defaultHash,\n valueEq = defaultEq,\n } = options;\n\n const capacity = this.nextPowerOfTwo(Math.max(4, initialCapacity));\n this._buckets = new Array(capacity).fill(null);\n this._size = 0;\n this._loadFactor = loadFactor;\n this._keyEq = keyEq;\n this._keyHash = keyHash;\n this._valueEq = valueEq;\n this._threshold = Math.floor(capacity * loadFactor);\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get keyEq(): Eq<K> {\n return this._keyEq;\n }\n\n get valueEq(): Eq<V> {\n return this._valueEq;\n }\n\n // ========================================================================\n // Lookup\n // ========================================================================\n\n has(key: K): boolean {\n return this.findNode(key) !== null;\n }\n\n get(key: K): V {\n // The node, not the value, tells if the key is present: a key can have the value undefined (C8)\n const node = this.findNode(key);\n if (node === null) {\n throw new Error(`Key not found: ${key}`);\n }\n return node.value;\n }\n\n getOrUndefined(key: K): V | undefined {\n return this.findNode(key)?.value;\n }\n\n getOrDefault(key: K, defaultValue: V): V {\n const node = this.findNode(key);\n return node !== null ? node.value : defaultValue;\n }\n\n /** This method finds the node of a key, or gives `null`. */\n private findNode(key: K): Node<K, V> | null {\n const hash = this._keyHash(key);\n let node = this._buckets[this.bucketIndex(hash)] ?? null;\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) return node;\n node = node.next;\n }\n return null;\n }\n\n containsValue(value: V): boolean {\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n if (this._valueEq(node.value, value)) {\n return true;\n }\n node = node.next;\n }\n }\n return false;\n }\n\n // ========================================================================\n // Modification\n // ========================================================================\n\n set(key: K, value: V): V | undefined {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n\n // Check if key already exists\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) {\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n }\n node = node.next;\n }\n\n // Key doesn't exist, add new entry\n const newNode: Node<K, V> = {\n key,\n value,\n hash,\n next: this._buckets[index] ?? null,\n };\n this._buckets[index] = newNode;\n this._size++;\n this._modCount++;\n\n // Check if resize is needed\n if (this._size > this._threshold) {\n this.resize();\n }\n\n return undefined;\n }\n\n setIfAbsent(key: K, value: V): V {\n const existing = this.getOrUndefined(key);\n if (existing !== undefined) {\n return existing;\n }\n this.set(key, value);\n return value;\n }\n\n delete(key: K): V | undefined {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n let prev: Node<K, V> | null = null;\n\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) {\n // Found the node to delete\n if (prev === null) {\n // Node is at head of bucket\n this._buckets[index] = node.next;\n } else {\n // Node is in middle or end\n prev.next = node.next;\n }\n this._size--;\n this._modCount++;\n return node.value;\n }\n prev = node;\n node = node.next;\n }\n\n return undefined;\n }\n\n deleteEntry(key: K, value: V): boolean {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n let prev: Node<K, V> | null = null;\n\n while (node !== null) {\n if (\n node.hash === hash &&\n this._keyEq(node.key, key) &&\n this._valueEq(node.value, value)\n ) {\n // Found the entry to delete\n if (prev === null) {\n this._buckets[index] = node.next;\n } else {\n prev.next = node.next;\n }\n this._size--;\n this._modCount++;\n return true;\n }\n prev = node;\n node = node.next;\n }\n\n return false;\n }\n\n replace(key: K, value: V): V | undefined {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) {\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n }\n node = node.next;\n }\n\n return undefined;\n }\n\n replaceEntry(key: K, oldValue: V, newValue: V): boolean {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n\n while (node !== null) {\n if (\n node.hash === hash &&\n this._keyEq(node.key, key) &&\n this._valueEq(node.value, oldValue)\n ) {\n node.value = newValue;\n return true;\n }\n node = node.next;\n }\n\n return false;\n }\n\n // ========================================================================\n // Compute operations\n // ========================================================================\n\n computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {\n const existing = this.getOrUndefined(key);\n if (existing !== undefined) {\n return existing;\n }\n\n const newValue = mappingFunction(key);\n this.set(key, newValue);\n return newValue;\n }\n\n computeIfPresent(\n key: K,\n remappingFunction: (key: K, value: V) => V | undefined\n ): V | undefined {\n const existing = this.getOrUndefined(key);\n if (existing === undefined) {\n return undefined;\n }\n\n const newValue = remappingFunction(key, existing);\n if (newValue === undefined) {\n this.delete(key);\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n compute(\n key: K,\n remappingFunction: (key: K, value: V | undefined) => V | undefined\n ): V | undefined {\n const existing = this.getOrUndefined(key);\n const newValue = remappingFunction(key, existing);\n\n if (newValue === undefined) {\n if (existing !== undefined) {\n this.delete(key);\n }\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n merge(\n key: K,\n value: V,\n remappingFunction: (oldValue: V, newValue: V) => V | undefined\n ): V | undefined {\n const existing = this.getOrUndefined(key);\n\n if (existing === undefined) {\n this.set(key, value);\n return value;\n }\n\n const merged = remappingFunction(existing, value);\n if (merged === undefined) {\n this.delete(key);\n return undefined;\n }\n\n this.set(key, merged);\n return merged;\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n putAll(other: MapLike<K, V> | Iterable<Entry<K, V>>): void {\n for (const entry of other) {\n this.set(entry.key, entry.value);\n }\n }\n\n clear(): void {\n this._buckets.fill(null);\n this._size = 0;\n this._modCount++;\n }\n\n // ========================================================================\n // Views\n // ========================================================================\n\n *keys(): IterableIterator<K> {\n const expected = this._modCount;\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n yield node.key;\n this.checkUnchanged(expected);\n node = node.next;\n }\n }\n }\n\n *values(): IterableIterator<V> {\n const expected = this._modCount;\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n yield node.value;\n this.checkUnchanged(expected);\n node = node.next;\n }\n }\n }\n\n *entries(): IterableIterator<Entry<K, V>> {\n const expected = this._modCount;\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n yield { key: node.key, value: node.value };\n this.checkUnchanged(expected);\n node = node.next;\n }\n }\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<Entry<K, V>> {\n yield* this.entries();\n }\n\n forEach(action: (value: V, key: K, map: this) => void): void {\n for (const entry of this.entries()) {\n action(entry.value, entry.key, this);\n }\n }\n\n // ========================================================================\n // Internal helpers\n // ========================================================================\n\n /** This method throws when the map changed structurally after an iterator started. */\n private checkUnchanged(expected: number): void {\n if (this._modCount !== expected) {\n throw new Error(\"HashMap changed during iteration\");\n }\n }\n\n /**\n * This method gives the bucket index for a given hash.\n */\n private bucketIndex(hash: number): number {\n // Use bitwise AND with (length - 1) for efficient modulo\n // This works because length is always a power of 2\n return hash & (this._buckets.length - 1);\n }\n\n /**\n * This method resizes the hash table to double its current capacity.\n */\n private resize(): void {\n const oldBuckets = this._buckets;\n const newCapacity = oldBuckets.length << 1; // Double capacity\n\n if (newCapacity < 0) {\n throw new Error(\"Map too large\");\n }\n\n this._buckets = new Array(newCapacity).fill(null);\n this._threshold = Math.floor(newCapacity * this._loadFactor);\n this._modCount++;\n\n // Rehash all entries\n for (const bucket of oldBuckets) {\n let node = bucket;\n while (node !== null) {\n const next = node.next;\n const index = this.bucketIndex(node.hash);\n node.next = this._buckets[index] ?? null;\n this._buckets[index] = node;\n node = next;\n }\n }\n }\n\n /**\n * This method gives the next power of 2 >= n.\n */\n private nextPowerOfTwo(n: number): number {\n if (n <= 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n return n + 1;\n }\n\n // ========================================================================\n // Inspection\n // ========================================================================\n\n /**\n * This value is the current number of buckets.\n */\n get capacity(): number {\n return this._buckets.length;\n }\n\n /**\n * This value is the current load factor (size / capacity).\n */\n get loadFactor(): number {\n return this._size / this._buckets.length;\n }\n\n /**\n * This method gives statistics about bucket distribution (for debugging).\n */\n getStats(): {\n size: number;\n capacity: number;\n loadFactor: number;\n avgChainLength: number;\n maxChainLength: number;\n emptyBuckets: number;\n } {\n let maxChainLength = 0;\n let totalChainLength = 0;\n let emptyBuckets = 0;\n\n for (const bucket of this._buckets) {\n if (bucket === null) {\n emptyBuckets++;\n } else {\n let length = 0;\n let node: Node<K, V> | null = bucket;\n while (node !== null) {\n length++;\n node = node.next;\n }\n totalChainLength += length;\n maxChainLength = Math.max(maxChainLength, length);\n }\n }\n\n return {\n size: this._size,\n capacity: this._buckets.length,\n loadFactor: this.loadFactor,\n avgChainLength: this._size > 0 ? totalChainLength / (this._buckets.length - emptyBuckets) : 0,\n maxChainLength,\n emptyBuckets,\n };\n }\n}\n\n/**\n * Factory function to make a HashMap.\n *\n * @example\n * const map = hashMap<string, number>()\n * const mapWithOptions = hashMap<User, Data>({\n * keyEq: (a, b) => a.id === b.id,\n * keyHash: (u) => hashString(u.id)\n * })\n * const mapFromEntries = hashMap([['a', 1], ['b', 2]])\n */\nexport function hashMap<K, V>(\n optionsOrEntries?: HashMapOptions<K, V> | Iterable<readonly [K, V]>\n): HashMap<K, V> {\n // Check if it's an iterable of entries\n if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {\n const map = new HashMap<K, V>();\n for (const [key, value] of optionsOrEntries as Iterable<readonly [K, V]>) {\n map.set(key, value);\n }\n return map;\n }\n\n return new HashMap<K, V>(optionsOrEntries as HashMapOptions<K, V>);\n}\n","/**\n * LinkedHashMap - HashMap that maintains insertion order.\n *\n * This module combines a hash table with a doubly-linked list to maintain predictable\n * iteration order. Mirrors java.util.LinkedHashMap.\n *\n * Key features:\n * - O(1) access, insert, delete (like HashMap)\n * - Predictable iteration order (insertion order or access order)\n * - Perfect for LRU caches when accessOrder is true\n *\n * @example\n * const map = linkedHashMap<string, number>()\n * map.set('a', 1)\n * map.set('b', 2)\n * map.set('c', 3)\n * // Iteration order: a, b, c (insertion order)\n *\n * @example\n * // LRU cache with access order\n * const lru = linkedHashMap<string, number>({ accessOrder: true })\n * lru.set('a', 1)\n * lru.set('b', 2)\n * lru.get('a') // Moves 'a' to end\n * // Iteration order: b, a (access order)\n */\n\nimport type { MapLike, Entry } from \"../interfaces/map.js\";\nimport type { Eq, Hash } from \"../core/traits.js\";\nimport { defaultEq, defaultHash } from \"../utils/defaults.js\";\n\n/**\n * An entry. It is in two lists: the chain of its hash bucket (`next`) and the order list\n * (`before`, `after`). Before, one `next` field served both lists, so the first collision or\n * resize corrupted the map (BUGS-2026-07 C10).\n */\ninterface LinkedNode<K, V> {\n key: K;\n value: V;\n hash: number;\n /** The next entry of the same hash bucket */\n next: LinkedNode<K, V> | null;\n /** The entry before this one in the iteration order */\n before: LinkedNode<K, V> | null;\n /** The entry after this one in the iteration order */\n after: LinkedNode<K, V> | null;\n}\n\n/**\n * Options for making a LinkedHashMap.\n */\nexport interface LinkedHashMapOptions<K, V> {\n /**\n * Initial capacity of the hash table.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * This option is the load factor before a resize.\n * @default 0.75\n */\n loadFactor?: number;\n\n /**\n * Equality function for keys.\n * @default defaultEq\n */\n eq?: Eq<K>;\n\n /**\n * Hash function for keys.\n * @default defaultHash\n */\n hash?: Hash<K>;\n\n /**\n * Equality function for values.\n * @default defaultEq\n */\n valueEq?: Eq<V>;\n\n /**\n * If true, maintain access order instead of insertion order.\n * Useful for LRU caches.\n * @default false\n */\n accessOrder?: boolean;\n}\n\n/**\n * LinkedHashMap<K, V> - Hash map with predictable iteration order.\n *\n * This class maintains a doubly-linked list of entries to preserve insertion order\n * (or access order if accessOrder is true).\n */\nexport class LinkedHashMap<K, V> implements MapLike<K, V> {\n private _buckets: (LinkedNode<K, V> | null)[];\n private _size: number = 0;\n private readonly _loadFactor: number;\n private readonly _eq: Eq<K>;\n private readonly _hash: Hash<K>;\n private readonly _valueEq: Eq<V>;\n private readonly _accessOrder: boolean;\n\n // Doubly-linked list sentinels\n private _head: LinkedNode<K, V> | null = null;\n private _tail: LinkedNode<K, V> | null = null;\n\n constructor(options: LinkedHashMapOptions<K, V> = {}) {\n const {\n initialCapacity = 16,\n loadFactor = 0.75,\n eq = defaultEq,\n hash = defaultHash,\n valueEq = defaultEq,\n accessOrder = false,\n } = options;\n\n this._buckets = new Array(Math.max(1, initialCapacity)).fill(null);\n this._loadFactor = loadFactor;\n this._eq = eq;\n this._hash = hash;\n this._valueEq = valueEq;\n this._accessOrder = accessOrder;\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get eq(): Eq<K> {\n return this._eq;\n }\n\n get keyEq(): Eq<K> {\n return this._eq;\n }\n\n get valueEq(): Eq<V> {\n return this._valueEq;\n }\n\n get hash(): Hash<K> {\n return this._hash;\n }\n\n // ========================================================================\n // Lookup operations\n // ========================================================================\n\n has(key: K): boolean {\n return this.getNode(key) !== null;\n }\n\n containsKey(key: K): boolean {\n return this.has(key);\n }\n\n containsValue(value: V): boolean {\n let node = this._head;\n while (node !== null) {\n if (this._valueEq(node.value, value)) {\n return true;\n }\n node = node.after;\n }\n return false;\n }\n\n get(key: K): V {\n const node = this.getNode(key);\n if (node === null) {\n throw new Error(\"Key not found\");\n }\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return node.value;\n }\n\n getOrUndefined(key: K): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return node.value;\n }\n\n getOrDefault(key: K, defaultValue: V): V {\n const node = this.getNode(key);\n if (node === null) return defaultValue;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return node.value;\n }\n\n // ========================================================================\n // Modification operations\n // ========================================================================\n\n set(key: K, value: V): V | undefined {\n const hashCode = this._hash(key);\n const index = this.getBucketIndex(hashCode);\n let node = this._buckets[index] ?? null;\n\n // Check if key already exists\n while (node !== null) {\n if (node.hash === hashCode && this._eq(node.key, key)) {\n const oldValue = node.value;\n node.value = value;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return oldValue;\n }\n node = node.next;\n }\n\n // Key doesn't exist, add new entry\n const newNode: LinkedNode<K, V> = {\n key,\n value,\n hash: hashCode,\n next: this._buckets[index] ?? null,\n before: null,\n after: null,\n };\n\n this._buckets[index] = newNode;\n this._size++;\n\n // Add to linked list\n this.addToEnd(newNode);\n\n // Resize if needed\n if (this._size > this._buckets.length * this._loadFactor) {\n this.resize();\n }\n\n return undefined;\n }\n\n setIfAbsent(key: K, value: V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return existing.value;\n }\n this.set(key, value);\n return value;\n }\n\n replace(key: K, value: V): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n const oldValue = node.value;\n node.value = value;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return oldValue;\n }\n\n replaceEntry(key: K, oldValue: V, newValue: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, oldValue)) {\n return false;\n }\n node.value = newValue;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return true;\n }\n\n delete(key: K): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n\n const oldValue = node.value;\n\n // Remove from bucket\n this.removeFromBucket(node);\n\n // Remove from linked list\n this.removeFromList(node);\n\n this._size--;\n return oldValue;\n }\n\n deleteEntry(key: K, value: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, value)) {\n return false;\n }\n\n // Remove from bucket\n this.removeFromBucket(node);\n\n // Remove from linked list\n this.removeFromList(node);\n\n this._size--;\n return true;\n }\n\n clear(): void {\n this._buckets = new Array(this._buckets.length).fill(null);\n this._size = 0;\n this._head = null;\n this._tail = null;\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n putAll(other: MapLike<K, V> | Iterable<Entry<K, V>>): void {\n if ('entries' in other && typeof other.entries === 'function') {\n for (const entry of other.entries()) {\n this.set(entry.key, entry.value);\n }\n } else {\n for (const entry of other as Iterable<Entry<K, V>>) {\n this.set(entry.key, entry.value);\n }\n }\n }\n\n // ========================================================================\n // Computed operations\n // ========================================================================\n\n computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return existing.value;\n }\n const value = mappingFunction(key);\n this.set(key, value);\n return value;\n }\n\n computeIfPresent(key: K, remappingFunction: (key: K, value: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n if (existing === null) return undefined;\n\n const newValue = remappingFunction(key, existing.value);\n if (newValue === undefined) {\n this.delete(key);\n return undefined;\n }\n existing.value = newValue;\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return newValue;\n }\n\n compute(key: K, remappingFunction: (key: K, value: V | undefined) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n const newValue = remappingFunction(key, existing?.value);\n\n if (newValue === undefined) {\n if (existing !== null) {\n this.delete(key);\n }\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n merge(key: K, value: V, remappingFunction: (oldValue: V, newValue: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n\n if (existing === null) {\n this.set(key, value);\n return value;\n }\n\n const merged = remappingFunction(existing.value, value);\n if (merged === undefined) {\n this.delete(key);\n return undefined;\n }\n\n existing.value = merged;\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return merged;\n }\n\n // ========================================================================\n // View operations\n // ========================================================================\n\n *keys(): IterableIterator<K> {\n let node = this._head;\n while (node !== null) {\n yield node.key;\n node = node.after;\n }\n }\n\n *values(): IterableIterator<V> {\n let node = this._head;\n while (node !== null) {\n yield node.value;\n node = node.after;\n }\n }\n\n *entries(): IterableIterator<Entry<K, V>> {\n let node = this._head;\n while (node !== null) {\n yield { key: node.key, value: node.value };\n node = node.after;\n }\n }\n\n *[Symbol.iterator](): Iterator<Entry<K, V>> {\n yield* this.entries();\n }\n\n forEach(action: (value: V, key: K, map: this) => void): void {\n for (const entry of this.entries()) {\n action(entry.value, entry.key, this);\n }\n }\n\n toArray(): Entry<K, V>[] {\n return Array.from(this.entries());\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n private getNode(key: K): LinkedNode<K, V> | null {\n const hashCode = this._hash(key);\n const index = this.getBucketIndex(hashCode);\n let node = this._buckets[index] ?? null;\n\n while (node !== null) {\n if (node.hash === hashCode && this._eq(node.key, key)) {\n return node;\n }\n node = node.next;\n }\n\n return null;\n }\n\n private getBucketIndex(hashCode: number): number {\n return Math.abs(hashCode) % this._buckets.length;\n }\n\n private removeFromBucket(node: LinkedNode<K, V>): void {\n const index = this.getBucketIndex(node.hash);\n let current = this._buckets[index] ?? null;\n let prev: LinkedNode<K, V> | null = null;\n\n while (current !== null) {\n if (current === node) {\n if (prev === null) {\n this._buckets[index] = current.next;\n } else {\n prev.next = current.next;\n }\n return;\n }\n prev = current;\n current = current.next;\n }\n }\n\n private addToEnd(node: LinkedNode<K, V>): void {\n node.before = this._tail;\n node.after = null;\n if (this._tail === null) this._head = node;\n else this._tail.after = node;\n this._tail = node;\n }\n\n private removeFromList(node: LinkedNode<K, V>): void {\n if (node.before !== null) node.before.after = node.after;\n else this._head = node.after;\n if (node.after !== null) node.after.before = node.before;\n else this._tail = node.before;\n node.before = node.after = null;\n }\n\n private moveToEnd(node: LinkedNode<K, V>): void {\n if (node === this._tail) return; // Already at end\n this.removeFromList(node);\n this.addToEnd(node);\n }\n\n private resize(): void {\n this._buckets = new Array(this._buckets.length * 2).fill(null);\n // Rebuild the bucket chains (`next`) from the order list (`after`)\n for (let node = this._head; node !== null; node = node.after) {\n const index = this.getBucketIndex(node.hash);\n node.next = this._buckets[index] ?? null;\n this._buckets[index] = node;\n }\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n toString(): string {\n const entries = Array.from(this.entries())\n .map(({ key, value }) => `${key}=${value}`)\n .join(', ');\n return `LinkedHashMap{${entries}}`;\n }\n}\n\n/**\n * Factory function to make a LinkedHashMap.\n *\n * @example\n * const map = linkedHashMap<string, number>()\n * map.set('a', 1)\n * map.set('b', 2)\n *\n * @example\n * // With initial entries\n * const map = linkedHashMap<string, number>([\n * ['a', 1],\n * ['b', 2]\n * ])\n *\n * @example\n * // LRU cache with access order\n * const lru = linkedHashMap<string, number>({ accessOrder: true })\n */\nexport function linkedHashMap<K, V>(\n optionsOrEntries?: LinkedHashMapOptions<K, V> | Iterable<[K, V]>\n): LinkedHashMap<K, V> {\n if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {\n const map = new LinkedHashMap<K, V>();\n for (const [key, value] of optionsOrEntries as Iterable<[K, V]>) {\n map.set(key, value);\n }\n return map;\n }\n\n return new LinkedHashMap<K, V>(optionsOrEntries as LinkedHashMapOptions<K, V>);\n}\n","/**\n * TreeMap - Red-black tree based sorted map implementation.\n *\n * This module implements a self-balancing binary search tree that maintains keys in sorted\n * order. Mirrors java.util.TreeMap.\n *\n * Key features:\n * - O(log n) access, insert, delete\n * - Keys maintained in sorted order (natural or custom comparator)\n * - Navigation methods (floor, ceiling, lower, higher)\n * - Range view operations (subMap, headMap, tailMap)\n *\n * @example\n * const map = treeMap<string, number>()\n * map.set('c', 3)\n * map.set('a', 1)\n * map.set('b', 2)\n * // Iteration order: a, b, c (sorted)\n *\n * @example\n * // Custom comparator for descending order\n * const map = treeMap<number, string>({\n * compare: (a, b) => b - a\n * })\n */\n\nimport type { NavigableMap, SortedMap, Entry } from \"../interfaces/map.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Node color in red-black tree.\n */\nconst Color = {\n RED: \"RED\",\n BLACK: \"BLACK\",\n} as const;\ntype Color = (typeof Color)[keyof typeof Color];\n\n/**\n * Node in the red-black tree.\n */\ninterface TreeNode<K, V> {\n key: K;\n value: V;\n color: Color;\n left: TreeNode<K, V> | null;\n right: TreeNode<K, V> | null;\n parent: TreeNode<K, V> | null;\n}\n\n// Null-safe helpers of the red-black algorithms: a null leaf is black\nfunction colorOf<K, V>(node: TreeNode<K, V> | null): Color {\n return node === null ? Color.BLACK : node.color;\n}\nfunction parentOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {\n return node === null ? null : node.parent;\n}\nfunction leftOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {\n return node === null ? null : node.left;\n}\nfunction rightOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {\n return node === null ? null : node.right;\n}\nfunction setColor<K, V>(node: TreeNode<K, V> | null, color: Color): void {\n if (node !== null) node.color = color;\n}\n\n/**\n * Options for making a TreeMap.\n */\nexport interface TreeMapOptions<K, V> {\n /**\n * Comparison function for keys.\n * @default defaultCompare\n */\n compare?: Compare<K>;\n\n /**\n * Equality function for keys.\n * @default defaultEq\n */\n eq?: Eq<K>;\n\n /**\n * Equality function for values.\n * @default defaultEq\n */\n valueEq?: Eq<V>;\n}\n\n/**\n * TreeMap<K, V> - Red-black tree based sorted map.\n *\n * Maintains keys in sorted order using a self-balancing binary search tree.\n * This class gives O(log n) operations and navigation methods.\n */\nexport class TreeMap<K, V> implements NavigableMap<K, V> {\n private _root: TreeNode<K, V> | null = null;\n private _size: number = 0;\n private readonly _compare: Compare<K>;\n private readonly _eq: Eq<K>;\n private readonly _valueEq: Eq<V>;\n\n constructor(options: TreeMapOptions<K, V> = {}) {\n const {\n compare = defaultCompare,\n eq = defaultEq,\n valueEq = defaultEq,\n } = options;\n\n this._compare = compare;\n this._eq = eq;\n this._valueEq = valueEq;\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get comparator(): Compare<K> {\n return this._compare;\n }\n\n get keyEq(): Eq<K> {\n return this._eq;\n }\n\n get valueEq(): Eq<V> {\n return this._valueEq;\n }\n\n // ========================================================================\n // Lookup operations\n // ========================================================================\n\n has(key: K): boolean {\n return this.getNode(key) !== null;\n }\n\n containsKey(key: K): boolean {\n return this.has(key);\n }\n\n containsValue(value: V): boolean {\n return this.findValue(this._root, value);\n }\n\n get(key: K): V {\n const node = this.getNode(key);\n if (node === null) {\n throw new Error(\"Key not found\");\n }\n return node.value;\n }\n\n getOrUndefined(key: K): V | undefined {\n const node = this.getNode(key);\n return node?.value;\n }\n\n getOrDefault(key: K, defaultValue: V): V {\n const node = this.getNode(key);\n return node !== null ? node.value : defaultValue;\n }\n\n // ========================================================================\n // Modification operations\n // ========================================================================\n\n set(key: K, value: V): V | undefined {\n if (this._root === null) {\n this._root = this.createNode(key, value, Color.BLACK);\n this._size++;\n return undefined;\n }\n\n // Find insertion point\n let node: TreeNode<K, V> | null = this._root;\n let parent: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n parent = node;\n const cmp = this._compare(key, node.key);\n\n if (cmp === 0) {\n // Key exists, replace value\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n node = node.right;\n }\n }\n\n // Insert new node\n const newNode = this.createNode(key, value, Color.RED);\n newNode.parent = parent;\n\n if (parent !== null) {\n const cmp = this._compare(key, parent.key);\n if (cmp < 0) {\n parent.left = newNode;\n } else {\n parent.right = newNode;\n }\n }\n\n this._size++;\n this.fixAfterInsertion(newNode);\n return undefined;\n }\n\n setIfAbsent(key: K, value: V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n return existing.value;\n }\n this.set(key, value);\n return value;\n }\n\n replace(key: K, value: V): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n }\n\n replaceEntry(key: K, oldValue: V, newValue: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, oldValue)) {\n return false;\n }\n node.value = newValue;\n return true;\n }\n\n delete(key: K): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n\n const oldValue = node.value;\n this.deleteNode(node);\n this._size--;\n return oldValue;\n }\n\n deleteEntry(key: K, value: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, value)) {\n return false;\n }\n this.deleteNode(node);\n this._size--;\n return true;\n }\n\n clear(): void {\n this._root = null;\n this._size = 0;\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n putAll(other: NavigableMap<K, V> | Iterable<Entry<K, V>>): void {\n if ('entries' in other && typeof other.entries === 'function') {\n for (const entry of other.entries()) {\n this.set(entry.key, entry.value);\n }\n } else {\n for (const entry of other as Iterable<Entry<K, V>>) {\n this.set(entry.key, entry.value);\n }\n }\n }\n\n // ========================================================================\n // Computed operations\n // ========================================================================\n\n computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n return existing.value;\n }\n const value = mappingFunction(key);\n this.set(key, value);\n return value;\n }\n\n computeIfPresent(key: K, remappingFunction: (key: K, value: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n if (existing === null) return undefined;\n\n const newValue = remappingFunction(key, existing.value);\n if (newValue === undefined) {\n this.delete(key);\n return undefined;\n }\n existing.value = newValue;\n return newValue;\n }\n\n compute(key: K, remappingFunction: (key: K, value: V | undefined) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n const newValue = remappingFunction(key, existing?.value);\n\n if (newValue === undefined) {\n if (existing !== null) {\n this.delete(key);\n }\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n merge(key: K, value: V, remappingFunction: (oldValue: V, newValue: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n\n if (existing === null) {\n this.set(key, value);\n return value;\n }\n\n const merged = remappingFunction(existing.value, value);\n if (merged === undefined) {\n this.delete(key);\n return undefined;\n }\n\n existing.value = merged;\n return merged;\n }\n\n // ========================================================================\n // SortedMap operations\n // ========================================================================\n\n firstKey(): K {\n if (this._root === null) {\n throw new Error(\"Map is empty\");\n }\n return this.getFirstNode(this._root).key;\n }\n\n lastKey(): K {\n if (this._root === null) {\n throw new Error(\"Map is empty\");\n }\n return this.getLastNode(this._root).key;\n }\n\n headMap(toKey: K): SortedMap<K, V> {\n // Return a view (simplified: create new map with filtered entries)\n const result = new TreeMap<K, V>({\n compare: this._compare,\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n for (const entry of this.entries()) {\n if (this._compare(entry.key, toKey) < 0) {\n result.set(entry.key, entry.value);\n } else {\n break; // Keys are sorted, so we can stop\n }\n }\n\n return result;\n }\n\n tailMap(fromKey: K): SortedMap<K, V> {\n const result = new TreeMap<K, V>({\n compare: this._compare,\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n let started = false;\n for (const entry of this.entries()) {\n if (!started && this._compare(entry.key, fromKey) < 0) {\n continue;\n }\n started = true;\n result.set(entry.key, entry.value);\n }\n\n return result;\n }\n\n subMap(fromKey: K, toKey: K): SortedMap<K, V> {\n const result = new TreeMap<K, V>({\n compare: this._compare,\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n for (const entry of this.entries()) {\n const cmpFrom = this._compare(entry.key, fromKey);\n const cmpTo = this._compare(entry.key, toKey);\n\n if (cmpFrom >= 0 && cmpTo < 0) {\n result.set(entry.key, entry.value);\n } else if (cmpTo >= 0) {\n break; // Past the range\n }\n }\n\n return result;\n }\n\n // ========================================================================\n // NavigableMap operations\n // ========================================================================\n\n floorKey(key: K): K | undefined {\n return this.floorEntry(key)?.key;\n }\n\n ceilingKey(key: K): K | undefined {\n return this.ceilingEntry(key)?.key;\n }\n\n lowerKey(key: K): K | undefined {\n return this.lowerEntry(key)?.key;\n }\n\n higherKey(key: K): K | undefined {\n return this.higherEntry(key)?.key;\n }\n\n floorEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp === 0) {\n return { key: node.key, value: node.value };\n } else if (cmp < 0) {\n node = node.left;\n } else {\n result = node; // This node is <= key\n node = node.right;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n ceilingEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp === 0) {\n return { key: node.key, value: node.value };\n } else if (cmp > 0) {\n node = node.right;\n } else {\n result = node; // This node is >= key\n node = node.left;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n lowerEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp <= 0) {\n node = node.left;\n } else {\n result = node; // This node is < key\n node = node.right;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n higherEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp >= 0) {\n node = node.right;\n } else {\n result = node; // This node is > key\n node = node.left;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n firstEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getFirstNode(this._root);\n return { key: node.key, value: node.value };\n }\n\n lastEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getLastNode(this._root);\n return { key: node.key, value: node.value };\n }\n\n pollFirstEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getFirstNode(this._root);\n const entry = { key: node.key, value: node.value };\n this.deleteNode(node);\n this._size--;\n return entry;\n }\n\n pollLastEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getLastNode(this._root);\n const entry = { key: node.key, value: node.value };\n this.deleteNode(node);\n this._size--;\n return entry;\n }\n\n descendingMap(): NavigableMap<K, V> {\n // Create a new TreeMap with reversed comparator\n const reversed = new TreeMap<K, V>({\n compare: (a, b) => this._compare(b, a),\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n for (const entry of this.entries()) {\n reversed.set(entry.key, entry.value);\n }\n\n return reversed;\n }\n\n *descendingKeys(): IterableIterator<K> {\n yield* this.reverseInOrderTraversal(this._root, (node) => node.key);\n }\n\n // ========================================================================\n // View operations\n // ========================================================================\n\n *keys(): IterableIterator<K> {\n yield* this.inOrderTraversal(this._root, (node) => node.key);\n }\n\n *values(): IterableIterator<V> {\n yield* this.inOrderTraversal(this._root, (node) => node.value);\n }\n\n *entries(): IterableIterator<Entry<K, V>> {\n yield* this.inOrderTraversal(this._root, (node) => ({\n key: node.key,\n value: node.value,\n }));\n }\n\n *[Symbol.iterator](): Iterator<Entry<K, V>> {\n yield* this.entries();\n }\n\n forEach(action: (value: V, key: K, map: this) => void): void {\n for (const entry of this.entries()) {\n action(entry.value, entry.key, this);\n }\n }\n\n toArray(): Entry<K, V>[] {\n return Array.from(this.entries());\n }\n\n // ========================================================================\n // Private helpers - Tree operations\n // ========================================================================\n\n private createNode(key: K, value: V, color: Color): TreeNode<K, V> {\n return {\n key,\n value,\n color,\n left: null,\n right: null,\n parent: null,\n };\n }\n\n private getNode(key: K): TreeNode<K, V> | null {\n let node = this._root;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp === 0) {\n return node;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n node = node.right;\n }\n }\n\n return null;\n }\n\n private getFirstNode(node: TreeNode<K, V>): TreeNode<K, V> {\n while (node.left !== null) {\n node = node.left;\n }\n return node;\n }\n\n private getLastNode(node: TreeNode<K, V>): TreeNode<K, V> {\n while (node.right !== null) {\n node = node.right;\n }\n return node;\n }\n\n private findValue(node: TreeNode<K, V> | null, value: V): boolean {\n if (node === null) return false;\n if (this._valueEq(node.value, value)) return true;\n return this.findValue(node.left, value) || this.findValue(node.right, value);\n }\n\n private *inOrderTraversal<T>(\n node: TreeNode<K, V> | null,\n mapper: (node: TreeNode<K, V>) => T\n ): IterableIterator<T> {\n if (node === null) return;\n yield* this.inOrderTraversal(node.left, mapper);\n yield mapper(node);\n yield* this.inOrderTraversal(node.right, mapper);\n }\n\n private *reverseInOrderTraversal<T>(\n node: TreeNode<K, V> | null,\n mapper: (node: TreeNode<K, V>) => T\n ): IterableIterator<T> {\n if (node === null) return;\n yield* this.reverseInOrderTraversal(node.right, mapper);\n yield mapper(node);\n yield* this.reverseInOrderTraversal(node.left, mapper);\n }\n\n // ========================================================================\n // Private helpers - Red-black tree balancing\n // ========================================================================\n\n private rotateLeft(node: TreeNode<K, V> | null): void {\n if (node === null || node.right === null) return;\n const right = node.right;\n node.right = right.left;\n\n if (right.left !== null) {\n right.left.parent = node;\n }\n\n right.parent = node.parent;\n\n if (node.parent === null) {\n this._root = right;\n } else if (node === node.parent.left) {\n node.parent.left = right;\n } else {\n node.parent.right = right;\n }\n\n right.left = node;\n node.parent = right;\n }\n\n private rotateRight(node: TreeNode<K, V> | null): void {\n if (node === null || node.left === null) return;\n const left = node.left;\n node.left = left.right;\n\n if (left.right !== null) {\n left.right.parent = node;\n }\n\n left.parent = node.parent;\n\n if (node.parent === null) {\n this._root = left;\n } else if (node === node.parent.right) {\n node.parent.right = left;\n } else {\n node.parent.left = left;\n }\n\n left.right = node;\n node.parent = left;\n }\n\n private fixAfterInsertion(node: TreeNode<K, V>): void {\n while (node.parent !== null && node.parent.color === Color.RED) {\n if (node.parent === node.parent.parent?.left) {\n const uncle = node.parent.parent.right;\n\n if (uncle?.color === Color.RED) {\n // Case 1: Uncle is red\n node.parent.color = Color.BLACK;\n uncle.color = Color.BLACK;\n node.parent.parent.color = Color.RED;\n node = node.parent.parent;\n } else {\n if (node === node.parent.right) {\n // Case 2: Node is right child\n node = node.parent;\n this.rotateLeft(node);\n }\n // Case 3: Node is left child\n node.parent!.color = Color.BLACK;\n node.parent!.parent!.color = Color.RED;\n this.rotateRight(node.parent!.parent!);\n }\n } else {\n const uncle = node.parent.parent?.left ?? null;\n\n if (uncle?.color === Color.RED) {\n // Case 1: Uncle is red\n node.parent.color = Color.BLACK;\n uncle.color = Color.BLACK;\n node.parent.parent!.color = Color.RED;\n node = node.parent.parent!;\n } else {\n if (node === node.parent.left) {\n // Case 2: Node is left child\n node = node.parent;\n this.rotateRight(node);\n }\n // Case 3: Node is right child\n node.parent!.color = Color.BLACK;\n node.parent!.parent!.color = Color.RED;\n this.rotateLeft(node.parent!.parent!);\n }\n }\n }\n\n this._root!.color = Color.BLACK;\n }\n\n /**\n * This method deletes a node (the CLRS algorithm, as in java.util.TreeMap). A null leaf counts as black.\n *\n * Before (BUGS-2026-07 L10): the deletion of a black leaf skipped the fix-up, so the black\n * heights drifted and the tree became unbalanced. Also, the fix-up treated a null leaf as\n * \"not black\", so it chose the wrong case and rotated at null (a TypeError).\n */\n private deleteNode(target: TreeNode<K, V>): void {\n let node = target;\n // A node with two children takes the key and value of its successor, then the successor goes\n if (node.left !== null && node.right !== null) {\n const successor = this.getFirstNode(node.right);\n node.key = successor.key;\n node.value = successor.value;\n node = successor;\n }\n\n const replacement = node.left ?? node.right;\n if (replacement !== null) {\n replacement.parent = node.parent;\n if (node.parent === null) this._root = replacement;\n else if (node === node.parent.left) node.parent.left = replacement;\n else node.parent.right = replacement;\n node.left = node.right = node.parent = null;\n if (node.color === Color.BLACK) this.fixAfterDeletion(replacement);\n } else if (node.parent === null) {\n // The only node\n this._root = null;\n } else {\n // A leaf: it is its own phantom replacement during the fix-up, then it goes\n if (node.color === Color.BLACK) this.fixAfterDeletion(node);\n if (node.parent !== null) {\n if (node === node.parent.left) node.parent.left = null;\n else if (node === node.parent.right) node.parent.right = null;\n node.parent = null;\n }\n }\n }\n\n private fixAfterDeletion(start: TreeNode<K, V>): void {\n let x: TreeNode<K, V> | null = start;\n while (x !== this._root && colorOf(x) === Color.BLACK) {\n if (x === leftOf(parentOf(x))) {\n let sibling = rightOf(parentOf(x));\n if (colorOf(sibling) === Color.RED) {\n setColor(sibling, Color.BLACK);\n setColor(parentOf(x), Color.RED);\n this.rotateLeft(parentOf(x));\n sibling = rightOf(parentOf(x));\n }\n if (colorOf(leftOf(sibling)) === Color.BLACK && colorOf(rightOf(sibling)) === Color.BLACK) {\n setColor(sibling, Color.RED);\n x = parentOf(x);\n } else {\n if (colorOf(rightOf(sibling)) === Color.BLACK) {\n setColor(leftOf(sibling), Color.BLACK);\n setColor(sibling, Color.RED);\n this.rotateRight(sibling);\n sibling = rightOf(parentOf(x));\n }\n setColor(sibling, colorOf(parentOf(x)));\n setColor(parentOf(x), Color.BLACK);\n setColor(rightOf(sibling), Color.BLACK);\n this.rotateLeft(parentOf(x));\n x = this._root;\n }\n } else {\n let sibling = leftOf(parentOf(x));\n if (colorOf(sibling) === Color.RED) {\n setColor(sibling, Color.BLACK);\n setColor(parentOf(x), Color.RED);\n this.rotateRight(parentOf(x));\n sibling = leftOf(parentOf(x));\n }\n if (colorOf(rightOf(sibling)) === Color.BLACK && colorOf(leftOf(sibling)) === Color.BLACK) {\n setColor(sibling, Color.RED);\n x = parentOf(x);\n } else {\n if (colorOf(leftOf(sibling)) === Color.BLACK) {\n setColor(rightOf(sibling), Color.BLACK);\n setColor(sibling, Color.RED);\n this.rotateLeft(sibling);\n sibling = leftOf(parentOf(x));\n }\n setColor(sibling, colorOf(parentOf(x)));\n setColor(parentOf(x), Color.BLACK);\n setColor(leftOf(sibling), Color.BLACK);\n this.rotateRight(parentOf(x));\n x = this._root;\n }\n }\n }\n setColor(x, Color.BLACK);\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n toString(): string {\n const entries = Array.from(this.entries())\n .map(({ key, value }) => `${key}=${value}`)\n .join(', ');\n return `TreeMap{${entries}}`;\n }\n}\n\n/**\n * Factory function to make a TreeMap.\n *\n * @example\n * const map = treeMap<string, number>()\n * map.set('c', 3)\n * map.set('a', 1)\n * map.set('b', 2)\n * // Iteration order: a, b, c\n *\n * @example\n * // With initial entries\n * const map = treeMap<string, number>([\n * ['c', 3],\n * ['a', 1],\n * ['b', 2]\n * ])\n *\n * @example\n * // Custom comparator for descending order\n * const map = treeMap<number, string>({ compare: (a, b) => b - a })\n */\nexport function treeMap<K, V>(\n optionsOrEntries?: TreeMapOptions<K, V> | Iterable<[K, V]>\n): TreeMap<K, V> {\n if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {\n const map = new TreeMap<K, V>();\n for (const [key, value] of optionsOrEntries as Iterable<[K, V]>) {\n map.set(key, value);\n }\n return map;\n }\n\n return new TreeMap<K, V>(optionsOrEntries as TreeMapOptions<K, V>);\n}\n","/**\n * TreeSet - Red-black tree based sorted set implementation.\n *\n * This module implements a sorted set using TreeMap as the backing structure.\n * Mirrors java.util.TreeSet.\n *\n * Key features:\n * - O(log n) add, remove, contains\n * - Elements maintained in sorted order (natural or custom comparator)\n * - Navigation methods (floor, ceiling, lower, higher)\n * - Range view operations (subSet, headSet, tailSet)\n *\n * @example\n * const set = treeSet<string>()\n * set.add('c')\n * set.add('a')\n * set.add('b')\n * // Iteration order: a, b, c (sorted)\n *\n * @example\n * // Custom comparator for descending order\n * const set = treeSet<number>({\n * compare: (a, b) => b - a\n * })\n */\n\nimport type { SortedSet, NavigableSet } from \"../interfaces/set.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { TreeMap } from \"./tree-map.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Dummy value used for TreeMap backing.\n */\nconst PRESENT = true;\n\n/**\n * Options for making a TreeSet.\n */\nexport interface TreeSetOptions<T> {\n /**\n * Comparison function for elements.\n * @default defaultCompare\n */\n compare?: Compare<T>;\n\n /**\n * Equality function for elements.\n * @default defaultEq\n */\n eq?: Eq<T>;\n}\n\n/**\n * TreeSet<T> - Red-black tree based sorted set.\n *\n * Maintains elements in sorted order using a TreeMap as backing structure.\n * This class gives O(log n) operations and navigation methods.\n */\nexport class TreeSet<T> implements NavigableSet<T> {\n private readonly _map: TreeMap<T, boolean>;\n private readonly _compare: Compare<T>;\n private readonly _eq: Eq<T>;\n\n constructor(options: TreeSetOptions<T> = {}) {\n const {\n compare = defaultCompare,\n eq = defaultEq,\n } = options;\n\n this._compare = compare;\n this._eq = eq;\n this._map = new TreeMap<T, boolean>({\n compare,\n eq,\n });\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this._map.size;\n }\n\n get isEmpty(): boolean {\n return this._map.isEmpty;\n }\n\n get comparator(): Compare<T> {\n return this._compare;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Membership operations\n // ========================================================================\n\n has(element: T): boolean {\n return this._map.has(element);\n }\n\n contains(element: T): boolean {\n return this.has(element);\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n // ========================================================================\n // Modification operations\n // ========================================================================\n\n add(element: T): boolean {\n const oldValue = this._map.set(element, PRESENT);\n return oldValue === undefined; // Returns true if element was added (not already present)\n }\n\n remove(element: T): boolean {\n const removed = this._map.delete(element);\n return removed !== undefined;\n }\n\n clear(): void {\n this._map.clear();\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n addAll(elements: Iterable<T>): boolean {\n let modified = false;\n for (const element of elements) {\n if (this.add(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n removeAll(elements: Iterable<T>): boolean {\n let modified = false;\n for (const element of elements) {\n if (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(elements: Iterable<T>): boolean {\n const toRetain = this.setOf(elements);\n\n let modified = false;\n for (const element of Array.from(this)) {\n if (!toRetain.has(element)) {\n this.remove(element);\n modified = true;\n }\n }\n return modified;\n }\n\n // ========================================================================\n // Set operations\n // ========================================================================\n\n union(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n for (const element of this) {\n result.add(element);\n }\n for (const element of other) {\n result.add(element);\n }\n\n return result;\n }\n\n intersection(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (otherSet.has(element)) {\n result.add(element);\n }\n }\n\n return result;\n }\n\n difference(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (!otherSet.has(element)) {\n result.add(element);\n }\n }\n\n return result;\n }\n\n symmetricDifference(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n // Add all elements from this set\n for (const element of this) {\n result.add(element);\n }\n\n // Toggle each element of the other set one time, so a repeated element does not toggle back\n for (const element of this.setOf(other)) {\n if (result.has(element)) {\n result.remove(element);\n } else {\n result.add(element);\n }\n }\n\n return result;\n }\n\n isSubsetOf(other: Iterable<T>): boolean {\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (!otherSet.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * This method makes a set of the elements, with the comparator and the equality of this set.\n * Before, the set operations used a native `Set`, which compares with `===` and ignores the comparator.\n */\n private setOf(elements: Iterable<T>): TreeSet<T> {\n const set = new TreeSet<T>({ compare: this._compare, eq: this._eq });\n for (const element of elements) {\n set.add(element);\n }\n return set;\n }\n\n isSupersetOf(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n isDisjointFrom(other: Iterable<T>): boolean {\n for (const element of other) {\n if (this.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n // ========================================================================\n // SortedSet operations\n // ========================================================================\n\n first(): T {\n const key = this._map.firstKey();\n return key;\n }\n\n last(): T {\n const key = this._map.lastKey();\n return key;\n }\n\n headSet(toElement: T): SortedSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n for (const element of this) {\n if (this._compare(element, toElement) < 0) {\n result.add(element);\n } else {\n break; // Elements are sorted\n }\n }\n\n return result;\n }\n\n tailSet(fromElement: T): SortedSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n let started = false;\n for (const element of this) {\n if (!started && this._compare(element, fromElement) < 0) {\n continue;\n }\n started = true;\n result.add(element);\n }\n\n return result;\n }\n\n subSet(fromElement: T, toElement: T): SortedSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n for (const element of this) {\n const cmpFrom = this._compare(element, fromElement);\n const cmpTo = this._compare(element, toElement);\n\n if (cmpFrom >= 0 && cmpTo < 0) {\n result.add(element);\n } else if (cmpTo >= 0) {\n break; // Past the range\n }\n }\n\n return result;\n }\n\n // ========================================================================\n // NavigableSet operations\n // ========================================================================\n\n floor(element: T): T | undefined {\n return this._map.floorKey(element);\n }\n\n ceiling(element: T): T | undefined {\n return this._map.ceilingKey(element);\n }\n\n lower(element: T): T | undefined {\n return this._map.lowerKey(element);\n }\n\n higher(element: T): T | undefined {\n return this._map.higherKey(element);\n }\n\n pollFirst(): T | undefined {\n const entry = this._map.pollFirstEntry();\n return entry?.key;\n }\n\n pollLast(): T | undefined {\n const entry = this._map.pollLastEntry();\n return entry?.key;\n }\n\n descendingSet(): NavigableSet<T> {\n const reversed = new TreeSet<T>({\n compare: (a, b) => this._compare(b, a),\n eq: this._eq,\n });\n\n for (const element of this) {\n reversed.add(element);\n }\n\n return reversed;\n }\n\n *descendingIterator(): IterableIterator<T> {\n yield* this._map.descendingKeys();\n }\n\n // ========================================================================\n // View operations\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n yield* this._map.keys();\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let index = 0;\n for (const element of this) {\n action(element, index++);\n }\n }\n\n toArray(): T[] {\n return Array.from(this);\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n toString(): string {\n const elements = Array.from(this).join(', ');\n return `TreeSet{${elements}}`;\n }\n}\n\n/**\n * Factory function to make a TreeSet.\n *\n * @example\n * const set = treeSet<string>()\n * set.add('c')\n * set.add('a')\n * set.add('b')\n * // Iteration order: a, b, c\n *\n * @example\n * // With initial elements\n * const set = treeSet(['c', 'a', 'b'])\n * // Iteration order: a, b, c\n *\n * @example\n * // Custom comparator for descending order\n * const set = treeSet<number>({ compare: (a, b) => b - a })\n */\nexport function treeSet<T>(\n optionsOrElements?: TreeSetOptions<T> | Iterable<T>\n): TreeSet<T> {\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const set = new TreeSet<T>();\n for (const element of optionsOrElements as Iterable<T>) {\n set.add(element);\n }\n return set;\n }\n\n return new TreeSet<T>(optionsOrElements as TreeSetOptions<T>);\n}\n","/**\n * LinkedList implementation - A doubly-linked list.\n *\n * This module gives O(1) insertion/removal at both ends and at known positions.\n * Slower random access O(n) compared to ArrayList.\n * Mirrors java.util.LinkedList.\n *\n * @example\n * const list = linkedList<number>()\n * list.addFirst(1)\n * list.addLast(2)\n * list.add(3)\n */\n\nimport type { List } from \"../interfaces/list.js\";\nimport type { Deque } from \"../interfaces/queue.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Internal node structure for the linked list.\n */\nclass Node<T> {\n value: T;\n prev: Node<T> | null;\n next: Node<T> | null;\n\n constructor(value: T, prev: Node<T> | null = null, next: Node<T> | null = null) {\n this.value = value;\n this.prev = prev;\n this.next = next;\n }\n}\n\n/**\n * Options for making a LinkedList.\n */\nexport interface LinkedListOptions<T> {\n /**\n * Equality function for comparing elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n}\n\n/**\n * LinkedList<T> - Doubly-linked list implementation.\n *\n * Efficient for:\n * - Insertion/removal at ends: O(1)\n * - Insertion/removal at known position: O(1)\n * - Sequential iteration: O(n)\n *\n * Not efficient for:\n * - Random access by index: O(n)\n * - Search: O(n)\n *\n * This class implements both List and Deque interfaces.\n */\nexport class LinkedList<T> implements List<T>, Deque<T> {\n private _head: Node<T> | null = null;\n private _tail: Node<T> | null = null;\n private _size: number = 0;\n private readonly _eq: Eq<T>;\n\n constructor(options: LinkedListOptions<T> = {}) {\n const { eq = defaultEq } = options;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Deque operations (both ends)\n // ========================================================================\n\n addFirst(element: T): void {\n const newNode = new Node(element, null, this._head);\n if (this._head) {\n this._head.prev = newNode;\n }\n this._head = newNode;\n if (!this._tail) {\n this._tail = newNode;\n }\n this._size++;\n }\n\n addLast(element: T): void {\n const newNode = new Node(element, this._tail, null);\n if (this._tail) {\n this._tail.next = newNode;\n }\n this._tail = newNode;\n if (!this._head) {\n this._head = newNode;\n }\n this._size++;\n }\n\n removeFirst(): T {\n if (!this._head) {\n throw new Error(\"List is empty\");\n }\n return this.pollFirst()!;\n }\n\n removeLast(): T {\n if (!this._tail) {\n throw new Error(\"List is empty\");\n }\n return this.pollLast()!;\n }\n\n pollFirst(): T | undefined {\n if (!this._head) return undefined;\n\n const value = this._head.value;\n this._head = this._head.next;\n\n if (this._head) {\n this._head.prev = null;\n } else {\n this._tail = null;\n }\n\n this._size--;\n return value;\n }\n\n pollLast(): T | undefined {\n if (!this._tail) return undefined;\n\n const value = this._tail.value;\n this._tail = this._tail.prev;\n\n if (this._tail) {\n this._tail.next = null;\n } else {\n this._head = null;\n }\n\n this._size--;\n return value;\n }\n\n peekFirst(): T {\n if (!this._head) {\n throw new Error(\"List is empty\");\n }\n return this._head.value;\n }\n\n peekLast(): T {\n if (!this._tail) {\n throw new Error(\"List is empty\");\n }\n return this._tail.value;\n }\n\n peekFirstOrUndefined(): T | undefined {\n return this._head?.value;\n }\n\n peekLastOrUndefined(): T | undefined {\n return this._tail?.value;\n }\n\n offerFirst(element: T): boolean {\n this.addFirst(element);\n return true;\n }\n\n offerLast(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n // ========================================================================\n // Stack operations (LIFO at the end, as on a JavaScript array)\n // ========================================================================\n\n // push and pop work at the end, and shift/unshift at the front, in every collection of this\n // package. Before, they worked at the front here (the Java Deque rule), so a LinkedList used\n // as a List reversed the pushed elements (ARCHITECTURE-PROPOSALS P8).\n push(element: T): void {\n this.addLast(element);\n }\n\n pop(): T {\n return this.removeLast();\n }\n\n // ========================================================================\n // Queue operations (FIFO)\n // ========================================================================\n\n offer(element: T): boolean {\n return this.offerLast(element);\n }\n\n poll(): T {\n return this.removeFirst();\n }\n\n peek(): T {\n return this.peekFirst();\n }\n\n peekOrUndefined(): T | undefined {\n return this.peekFirstOrUndefined();\n }\n\n pollOrUndefined(): T | undefined {\n return this.pollFirst();\n }\n\n enqueue(element: T): boolean {\n return this.offer(element);\n }\n\n dequeue(): T {\n return this.poll();\n }\n\n // ========================================================================\n // List operations\n // ========================================================================\n\n get(index: number): T {\n const node = this.getNode(index);\n return node.value;\n }\n\n set(index: number, element: T): T {\n const node = this.getNode(index);\n const old = node.value;\n node.value = element;\n return old;\n }\n\n insert(index: number, element: T): void {\n if (index < 0 || index > this._size) {\n throw new RangeError(`Index ${index} out of bounds for size ${this._size}`);\n }\n\n if (index === 0) {\n this.addFirst(element);\n return;\n }\n\n if (index === this._size) {\n this.addLast(element);\n return;\n }\n\n const nextNode = this.getNode(index);\n const prevNode = nextNode.prev!;\n const newNode = new Node(element, prevNode, nextNode);\n\n prevNode.next = newNode;\n nextNode.prev = newNode;\n this._size++;\n }\n\n insertAll(index: number, other: Iterable<T>): boolean {\n if (index < 0 || index > this._size) {\n throw new RangeError(`Index ${index} out of bounds for size ${this._size}`);\n }\n\n const elements = Array.from(other);\n if (elements.length === 0) return false;\n\n for (let i = 0; i < elements.length; i++) {\n this.insert(index + i, elements[i]!);\n }\n\n return true;\n }\n\n removeAt(index: number): T {\n const node = this.getNode(index);\n return this.unlinkNode(node);\n }\n\n removeRange(fromIndex: number, toIndex: number): void {\n if (fromIndex < 0 || toIndex > this._size || fromIndex > toIndex) {\n throw new RangeError(`Invalid range [${fromIndex}, ${toIndex})`);\n }\n\n for (let i = fromIndex; i < toIndex; i++) {\n this.removeAt(fromIndex);\n }\n }\n\n indexOf(element: T, fromIndex: number = 0): number {\n let index = 0;\n let node = this._head;\n\n while (node) {\n if (index >= fromIndex && this._eq(node.value, element)) {\n return index;\n }\n node = node.next;\n index++;\n }\n\n return -1;\n }\n\n lastIndexOf(element: T, fromIndex?: number): number {\n const start = fromIndex !== undefined ? fromIndex : this._size - 1;\n let index = this._size - 1;\n let node = this._tail;\n\n while (node && index >= 0) {\n if (index <= start && this._eq(node.value, element)) {\n return index;\n }\n node = node.prev;\n index--;\n }\n\n return -1;\n }\n\n first(): T {\n return this.peekFirst();\n }\n\n last(): T {\n return this.peekLast();\n }\n\n shift(): T {\n return this.removeFirst();\n }\n\n unshift(element: T): void {\n this.addFirst(element);\n }\n\n // ========================================================================\n // Collection operations\n // ========================================================================\n\n add(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n this.addLast(element);\n modified = true;\n }\n return modified;\n }\n\n contains(element: T): boolean {\n return this.indexOf(element) !== -1;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) return false;\n }\n return true;\n }\n\n remove(element: T): boolean {\n let node = this._head;\n\n while (node) {\n if (this._eq(node.value, element)) {\n this.unlinkNode(node);\n return true;\n }\n node = node.next;\n }\n\n return false;\n }\n\n removeAll(other: Iterable<T>): boolean {\n const toRemove = new Set(other);\n let modified = false;\n\n for (const element of toRemove) {\n while (this.remove(element)) {\n modified = true;\n }\n }\n\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = new Set(other);\n let node = this._head;\n let modified = false;\n\n while (node) {\n const next = node.next;\n let shouldRetain = false;\n\n for (const retainElement of toRetain) {\n if (this._eq(node.value, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n\n if (!shouldRetain) {\n this.unlinkNode(node);\n modified = true;\n }\n\n node = next;\n }\n\n return modified;\n }\n\n clear(): void {\n this._head = null;\n this._tail = null;\n this._size = 0;\n }\n\n // ========================================================================\n // Sorting and reversing\n // ========================================================================\n\n sort(compare: Compare<T> = defaultCompare): void {\n if (this._size <= 1) return;\n\n // Convert to array, sort, rebuild list\n const array = this.toArray();\n array.sort(compare);\n\n this.clear();\n for (const element of array) {\n this.addLast(element);\n }\n }\n\n reverse(): void {\n if (this._size <= 1) return;\n\n let node = this._head;\n this._head = this._tail;\n this._tail = node;\n\n while (node) {\n const next = node.next;\n node.next = node.prev;\n node.prev = next;\n node = next;\n }\n }\n\n // ========================================================================\n // Views\n // ========================================================================\n\n subList(fromIndex: number, toIndex: number): List<T> {\n if (fromIndex < 0 || toIndex > this._size || fromIndex > toIndex) {\n throw new RangeError(`Invalid range [${fromIndex}, ${toIndex})`);\n }\n\n const sub = new LinkedList<T>({ eq: this._eq });\n let index = 0;\n let node = this._head;\n\n while (node && index < toIndex) {\n if (index >= fromIndex) {\n sub.addLast(node.value);\n }\n node = node.next;\n index++;\n }\n\n return sub;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n let node = this._head;\n while (node) {\n yield node.value;\n node = node.next;\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let index = 0;\n let node = this._head;\n\n while (node) {\n action(node.value, index);\n node = node.next;\n index++;\n }\n }\n\n toArray(): T[] {\n const result: T[] = [];\n let node = this._head;\n\n while (node) {\n result.push(node.value);\n node = node.next;\n }\n\n return result;\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n private getNode(index: number): Node<T> {\n if (index < 0 || index >= this._size) {\n throw new RangeError(`Index ${index} out of bounds for size ${this._size}`);\n }\n\n // Optimize: start from head or tail depending on index\n if (index < this._size / 2) {\n // Start from head\n let node = this._head!;\n for (let i = 0; i < index; i++) {\n node = node.next!;\n }\n return node;\n } else {\n // Start from tail\n let node = this._tail!;\n for (let i = this._size - 1; i > index; i--) {\n node = node.prev!;\n }\n return node;\n }\n }\n\n private unlinkNode(node: Node<T>): T {\n const value = node.value;\n\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this._head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this._tail = node.prev;\n }\n\n this._size--;\n return value;\n }\n\n // ========================================================================\n // Inspection\n // ========================================================================\n\n toString(): string {\n return `LinkedList[${this.toArray().join(\", \")}]`;\n }\n}\n\n/**\n * Factory function to make a LinkedList.\n *\n * @example\n * const list = linkedList<number>()\n * const listFromArray = linkedList([1, 2, 3])\n */\nexport function linkedList<T>(\n optionsOrElements?: LinkedListOptions<T> | Iterable<T>\n): LinkedList<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const list = new LinkedList<T>();\n list.addAll(optionsOrElements as Iterable<T>);\n return list;\n }\n\n return new LinkedList<T>(optionsOrElements as LinkedListOptions<T>);\n}\n","/**\n * HashSet implementation - A set backed by a HashMap.\n *\n * This module gives O(1) average case for add, remove, and contains operations.\n * Elements are unique based on custom equality and hash functions.\n * Mirrors java.util.HashSet.\n *\n * @example\n * const set = hashSet<number>()\n * set.add(1)\n * set.add(2)\n * set.add(1) // Returns false, already present\n * set.size // 2\n */\n\nimport type { Set } from \"../interfaces/set.js\";\nimport type { Eq, Hash } from \"../core/traits.js\";\nimport { HashMap } from \"./hash-map.js\";\nimport { defaultEq, defaultHash } from \"../utils/defaults.js\";\n\n/**\n * Dummy value used for the HashMap backing the set.\n */\nconst PRESENT = Symbol(\"PRESENT\");\n\n/**\n * Options for making a HashSet.\n */\nexport interface HashSetOptions<T> {\n /**\n * Initial capacity.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * This option is the load factor threshold for a resize.\n * @default 0.75\n */\n loadFactor?: number;\n\n /**\n * Equality function for elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n\n /**\n * Hash function for elements.\n * @default defaultHash\n */\n hash?: Hash<T>;\n}\n\n/**\n * HashSet<T> - Hash table implementation of the Set interface.\n *\n * A HashMap holds the elements. Its values are a dummy constant.\n * This class gives constant-time performance for basic operations.\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class HashSet<T> implements Set<T> {\n private readonly _map: HashMap<T, symbol>;\n private readonly _eq: Eq<T>;\n private readonly _hash: Hash<T>;\n\n constructor(options: HashSetOptions<T> = {}) {\n const {\n initialCapacity = 16,\n loadFactor = 0.75,\n eq = defaultEq,\n hash = defaultHash,\n } = options;\n\n this._eq = eq;\n this._hash = hash;\n this._map = new HashMap<T, symbol>({\n initialCapacity,\n loadFactor,\n keyEq: eq,\n keyHash: hash,\n });\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._map.size;\n }\n\n get isEmpty(): boolean {\n return this._map.isEmpty;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Core set operations\n // ========================================================================\n\n add(element: T): boolean {\n const hadElement = this._map.has(element);\n this._map.set(element, PRESENT);\n return !hadElement;\n }\n\n remove(element: T): boolean {\n return this._map.delete(element) !== undefined;\n }\n\n contains(element: T): boolean {\n return this._map.has(element);\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n if (this.add(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n removeAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n if (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = this.setOf(other);\n const toRemove: T[] = [];\n\n for (const element of this) {\n if (!toRetain.contains(element)) {\n toRemove.push(element);\n }\n }\n\n let modified = false;\n for (const element of toRemove) {\n this.remove(element);\n modified = true;\n }\n\n return modified;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n clear(): void {\n this._map.clear();\n }\n\n // ========================================================================\n // Set operations (mathematical)\n // ========================================================================\n\n /**\n * This method gives a new set that is the union of this set and the other set.\n * The new set contains all elements from both sets.\n */\n union(other: Iterable<T>): HashSet<T> {\n const result = this.clone();\n result.addAll(other);\n return result;\n }\n\n /**\n * This method gives a new set that is the intersection of this set and the other set.\n * The new set contains only elements present in both sets.\n */\n intersection(other: Iterable<T>): HashSet<T> {\n // The loop reads `other` one time, so a generator gives all of its elements\n const others = this.setOf(other);\n const result = this.empty();\n for (const element of this) {\n if (others.contains(element)) {\n result.add(element);\n }\n }\n return result;\n }\n\n /**\n * This method gives a new set that is the difference of this set and the other set.\n * The new set contains elements in this set but not in the other set.\n */\n difference(other: Iterable<T>): HashSet<T> {\n const result = this.clone();\n result.removeAll(other);\n return result;\n }\n\n /**\n * This method gives a new set that is the symmetric difference of this set and the other set.\n * The new set contains elements in either set but not in both.\n */\n symmetricDifference(other: Iterable<T>): HashSet<T> {\n // The union and the intersection each read `other`, so read it one time first\n const others = this.setOf(other);\n const result = this.union(others);\n const inter = this.intersection(others);\n result.removeAll(inter);\n return result;\n }\n\n /**\n * This method gives true if this set is a subset of the other set.\n * All elements in this set are also in the other set.\n */\n isSubsetOf(other: Iterable<T>): boolean {\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (!otherSet.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * This method gives true if this set is a superset of the other set.\n * All elements in the other set are also in this set.\n */\n isSupersetOf(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * This method gives true if this set and the other set have no elements in common.\n */\n isDisjointFrom(other: Iterable<T>): boolean {\n for (const element of other) {\n if (this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n for (const entry of this._map) {\n yield entry.key;\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let index = 0;\n for (const element of this) {\n action(element, index++);\n }\n }\n\n toArray(): T[] {\n return Array.from(this);\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n /**\n * This method makes a shallow copy of this set.\n */\n clone(): HashSet<T> {\n return this.setOf(this);\n }\n\n /**\n * This method makes an empty set with the equality and the hash function of this set.\n * Before, the inner sets kept only the equality, so they did not find an element with a custom hash.\n */\n private empty(): HashSet<T> {\n return new HashSet<T>({ eq: this._eq, hash: this._hash });\n }\n\n /** This method makes a set of the elements, with the equality and the hash function of this set. */\n private setOf(elements: Iterable<T>): HashSet<T> {\n const set = this.empty();\n set.addAll(elements);\n return set;\n }\n\n /**\n * This method gives statistics about the underlying hash table.\n */\n getStats(): ReturnType<HashMap<T, symbol>[\"getStats\"]> {\n return this._map.getStats();\n }\n\n /**\n * This method gives a string representation for debugging.\n */\n toString(): string {\n return `HashSet{${this.toArray().join(\", \")}}`;\n }\n}\n\n/**\n * Factory function to make a HashSet.\n *\n * @example\n * const set = hashSet<number>()\n * const setFromArray = hashSet([1, 2, 3, 2, 1]) // {1, 2, 3}\n * const setWithOptions = hashSet<string>({ initialCapacity: 32 })\n */\nexport function hashSet<T>(\n optionsOrElements?: HashSetOptions<T> | Iterable<T>\n): HashSet<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const set = new HashSet<T>();\n set.addAll(optionsOrElements as Iterable<T>);\n return set;\n }\n\n return new HashSet<T>(optionsOrElements as HashSetOptions<T>);\n}\n","/**\n * PriorityQueue implementation - A binary heap-based priority queue.\n *\n * Elements are ordered according to their natural ordering (through a comparator).\n * The head of the queue is the least element according to the comparator.\n * This module gives O(log n) enqueue and O(log n) dequeue operations.\n * Mirrors java.util.PriorityQueue.\n *\n * @example\n * const pq = priorityQueue<number>((a, b) => a - b) // Min heap\n * pq.offer(5)\n * pq.offer(2)\n * pq.offer(8)\n * pq.poll() // 2 (smallest element)\n */\n\nimport type { PriorityQueue as IPriorityQueue } from \"../interfaces/queue.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Options for making a PriorityQueue.\n */\nexport interface PriorityQueueOptions<T> {\n /**\n * Initial capacity of the heap.\n * @default 11\n */\n initialCapacity?: number;\n\n /**\n * Comparator for ordering elements.\n * Lower values have higher priority (min heap).\n * @default defaultCompare\n */\n compare?: Compare<T>;\n\n /**\n * Equality function for elements.\n * @default defaultEq\n */\n eq?: Eq<T>;\n}\n\n/**\n * PriorityQueue<T> - Binary heap implementation of priority queue.\n *\n * Elements are always retrieved in priority order (according to comparator).\n * Not a FIFO queue - order depends on priority, not insertion order.\n *\n * The heap is a min heap by default (smallest element has highest priority).\n * For max heap, use reversed comparator: (a, b) => compare(b, a)\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class PriorityQueue<T> implements IPriorityQueue<T> {\n private _heap: T[];\n private readonly _compare: Compare<T>;\n private readonly _eq: Eq<T>;\n\n constructor(options: PriorityQueueOptions<T> = {}) {\n const {\n compare = defaultCompare,\n eq = defaultEq,\n } = options;\n\n // The heap starts empty: a JavaScript array grows by itself, so initialCapacity is only a\n // hint. (Before, `new Array(initialCapacity)` made 11 holes: an empty queue had size 11,\n // and the heap compared holes. BUGS-2026-07 C9.)\n this._heap = [];\n this._compare = compare;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._heap.length;\n }\n\n get isEmpty(): boolean {\n return this._heap.length === 0;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n get compare(): Compare<T> {\n return this._compare;\n }\n\n get comparator(): Compare<T> {\n return this._compare;\n }\n\n // ========================================================================\n // Priority queue operations\n // ========================================================================\n\n offer(element: T): boolean {\n this._heap.push(element);\n this.bubbleUp(this._heap.length - 1);\n return true;\n }\n\n poll(): T {\n if (this.isEmpty) {\n throw new Error(\"Priority queue is empty\");\n }\n return this.pollOrUndefined()!;\n }\n\n pollOrUndefined(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n\n const result = this._heap[0];\n\n if (this._heap.length === 1) {\n this._heap.pop();\n } else {\n this._heap[0] = this._heap.pop()!;\n this.bubbleDown(0);\n }\n\n return result;\n }\n\n peek(): T {\n if (this.isEmpty) {\n throw new Error(\"Priority queue is empty\");\n }\n return this._heap[0]!;\n }\n\n peekOrUndefined(): T | undefined {\n return this.isEmpty ? undefined : this._heap[0];\n }\n\n // ========================================================================\n // Queue interface compatibility\n // ========================================================================\n\n enqueue(element: T): boolean {\n return this.offer(element);\n }\n\n dequeue(): T {\n return this.poll();\n }\n\n // ========================================================================\n // Collection operations\n // ========================================================================\n\n add(element: T): boolean {\n return this.offer(element);\n }\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n this.offer(element);\n modified = true;\n }\n return modified;\n }\n\n contains(element: T): boolean {\n for (const item of this._heap) {\n if (this._eq(item, element)) {\n return true;\n }\n }\n return false;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n remove(element: T): boolean {\n const index = this._heap.findIndex((item) => this._eq(item, element));\n if (index === -1) {\n return false;\n }\n\n if (index === this._heap.length - 1) {\n this._heap.pop();\n } else {\n this._heap[index] = this._heap.pop()!;\n this.bubbleDown(index);\n this.bubbleUp(index);\n }\n\n return true;\n }\n\n removeAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n while (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = new Set(other);\n const newHeap: T[] = [];\n\n for (const element of this._heap) {\n let shouldRetain = false;\n for (const retainElement of toRetain) {\n if (this._eq(element, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n if (shouldRetain) {\n newHeap.push(element);\n }\n }\n\n const modified = newHeap.length !== this._heap.length;\n this._heap = newHeap;\n this.heapify();\n\n return modified;\n }\n\n clear(): void {\n this._heap = [];\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n /**\n * Iterator gives elements in arbitrary order (not priority order).\n * To get elements in priority order, repeatedly call poll().\n */\n *[Symbol.iterator](): Iterator<T> {\n yield* this._heap;\n }\n\n forEach(action: (element: T, index: number) => void): void {\n this._heap.forEach((element, index) => action(element, index));\n }\n\n /**\n * This method gives elements in arbitrary heap order (not sorted).\n */\n toArray(): T[] {\n return this._heap.slice();\n }\n\n /**\n * This method gives elements in priority order (sorted).\n * This is a destructive operation that drains the queue.\n */\n toSortedArray(): T[] {\n const result: T[] = [];\n const clone = this.clone();\n\n while (!clone.isEmpty) {\n result.push(clone.poll());\n }\n\n return result;\n }\n\n // ========================================================================\n // Heap operations\n // ========================================================================\n\n /**\n * This method bubbles an element up the heap to maintain heap property.\n */\n private bubbleUp(index: number): void {\n const element = this._heap[index]!;\n\n while (index > 0) {\n const parentIndex = Math.floor((index - 1) / 2);\n const parent = this._heap[parentIndex]!;\n\n if (this._compare(element, parent) >= 0) {\n break;\n }\n\n this._heap[index] = parent;\n index = parentIndex;\n }\n\n this._heap[index] = element;\n }\n\n /**\n * This method bubbles an element down the heap to maintain heap property.\n *\n * The element moves down through a hole: a smaller child moves up into the hole, and the\n * element goes into the last hole. The children are compared with the element.\n * Before, they were compared with `_heap[index]`. After the first step, that value is a copy of\n * the child that moved up. Thus a poll could leave a larger element above a smaller one.\n */\n private bubbleDown(index: number): void {\n const length = this._heap.length;\n const element = this._heap[index]!;\n\n while (true) {\n const leftChildIndex = 2 * index + 1;\n const rightChildIndex = 2 * index + 2;\n if (leftChildIndex >= length) {\n break;\n }\n\n let childIndex = leftChildIndex;\n if (\n rightChildIndex < length &&\n this._compare(this._heap[rightChildIndex]!, this._heap[leftChildIndex]!) < 0\n ) {\n childIndex = rightChildIndex;\n }\n\n if (this._compare(this._heap[childIndex]!, element) >= 0) {\n break;\n }\n\n this._heap[index] = this._heap[childIndex]!;\n index = childIndex;\n }\n\n this._heap[index] = element;\n }\n\n /**\n * This method rebuilds the heap from an arbitrary array.\n * This method uses Floyd's algorithm (O(n) time).\n */\n private heapify(): void {\n // Start from last non-leaf node and bubble down\n for (let i = Math.floor(this._heap.length / 2) - 1; i >= 0; i--) {\n this.bubbleDown(i);\n }\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n /**\n * This method makes a shallow copy of this priority queue.\n */\n clone(): PriorityQueue<T> {\n const clone = new PriorityQueue<T>({\n compare: this._compare,\n eq: this._eq,\n });\n clone._heap = this._heap.slice();\n return clone;\n }\n\n /**\n * This method validates the heap property (for debugging).\n * This method gives true if the heap is valid.\n */\n validate(): boolean {\n for (let i = 0; i < this._heap.length; i++) {\n const leftChildIndex = 2 * i + 1;\n const rightChildIndex = 2 * i + 2;\n\n if (\n leftChildIndex < this._heap.length &&\n this._compare(this._heap[i]!, this._heap[leftChildIndex]!) > 0\n ) {\n return false;\n }\n\n if (\n rightChildIndex < this._heap.length &&\n this._compare(this._heap[i]!, this._heap[rightChildIndex]!) > 0\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * This method gives a string representation for debugging.\n */\n toString(): string {\n return `PriorityQueue[${this._heap.join(\", \")}]`;\n }\n}\n\n/**\n * Factory function to make a PriorityQueue.\n *\n * @example\n * // Min heap (default)\n * const minHeap = priorityQueue<number>()\n *\n * // Max heap\n * const maxHeap = priorityQueue<number>((a, b) => b - a)\n *\n * // From array\n * const pq = priorityQueue([5, 2, 8, 1, 9])\n *\n * // With custom comparator\n * const pq = priorityQueue<Task>((a, b) => a.priority - b.priority)\n */\nexport function priorityQueue<T>(\n optionsOrElementsOrComparator?:\n | PriorityQueueOptions<T>\n | Iterable<T>\n | Compare<T>\n): PriorityQueue<T> {\n // If it's a function, treat it as a comparator\n if (typeof optionsOrElementsOrComparator === \"function\") {\n return new PriorityQueue<T>({\n compare: optionsOrElementsOrComparator as Compare<T>,\n });\n }\n\n // Check if it's an iterable (not options)\n if (optionsOrElementsOrComparator && Symbol.iterator in optionsOrElementsOrComparator) {\n const pq = new PriorityQueue<T>();\n pq.addAll(optionsOrElementsOrComparator as Iterable<T>);\n return pq;\n }\n\n return new PriorityQueue<T>(\n optionsOrElementsOrComparator as PriorityQueueOptions<T>\n );\n}\n","/**\n * SummaryTree: the class form of the summary tree, a persistent sequence of leaves with a summary of each part.\n *\n * The class wraps the plain functions of the entry `@mark1russell7/collections/summary-tree`. Its `record` is the\n * plain record that those functions take. A bundle that uses the class keeps each of its methods, so a program that\n * calls only a few operations imports the functions instead.\n *\n * @example\n * // The number of leaves and the total length of the strings\n * const spec = {\n * monoid: { empty: { count: 0, length: 0 }, combine: (a, b) => ({ count: a.count + b.count, length: a.length + b.length }) },\n * measure: (leaf: string) => ({ count: 1, length: leaf.length }),\n * };\n * const tree = summaryTree(spec, [\"ab\", \"cde\", \"f\"]);\n * tree.summary; // { count: 3, length: 6 }\n * const [left, right] = tree.split((prefix) => prefix.length > 2); // left: [\"ab\"], right: [\"cde\", \"f\"]\n */\n\nimport * as Tree from \"../summary-tree/functions.js\";\nimport type { SummaryLocation, SummaryNode, SummarySearch, SummarySpec, SummaryTreeRecord } from \"../summary-tree/functions.js\";\n\nexport type { SummaryLocation, SummaryMonoid, SummaryNode, SummarySearch, SummarySpec, SummaryTreeRecord } from \"../summary-tree/functions.js\";\n\n/**\n * A persistent sequence of leaves with a summary of each part. Make one with `summaryTree`. Each method that changes\n * the sequence gives a new tree.\n */\nexport class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {\n /** The plain record of the tree: its spec and its root. The functions of the entry `./summary-tree` take it. */\n readonly record: SummaryTreeRecord<Leaf, Summary>;\n\n private constructor(record: SummaryTreeRecord<Leaf, Summary>) {\n this.record = record;\n }\n\n /** This function makes a tree of a spec from leaves, as `summaryTree` does. */\n static of<Leaf, Summary>(spec: SummarySpec<Leaf, Summary>, leaves: Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {\n return new SummaryTree(Tree.of(spec, leaves));\n }\n\n /** This function wraps a plain record of the entry `./summary-tree` in a tree. It does not copy the nodes. */\n static fromRecord<Leaf, Summary>(record: SummaryTreeRecord<Leaf, Summary>): SummaryTree<Leaf, Summary> {\n return new SummaryTree(record);\n }\n\n private wrap(record: SummaryTreeRecord<Leaf, Summary>): SummaryTree<Leaf, Summary> {\n return record === this.record ? this : new SummaryTree(record);\n }\n\n /** The spec of the tree: its monoid and its measure. */\n get spec(): SummarySpec<Leaf, Summary> {\n return this.record.spec;\n }\n\n /** The number of leaves. */\n get size(): number {\n return Tree.size(this.record);\n }\n\n get isEmpty(): boolean {\n return Tree.isEmpty(this.record);\n }\n\n /** The summary of all the leaves, in their order. An empty tree has the summary `monoid.empty`. */\n get summary(): Summary {\n return Tree.summary(this.record);\n }\n\n /** The height of the tree: 0 for an empty tree. The height is at most 1.45 log2(size + 2). */\n get height(): number {\n return Tree.height(this.record);\n }\n\n /**\n * This function gives the leaf at an index, or `undefined` when the index is not in the tree. A negative index counts\n * from the end, as `Array.prototype.at` does.\n */\n at(index: number): Leaf | undefined {\n return Tree.at(this.record, index);\n }\n\n /** This function gives the summary of the leaves from `start` to `end`, with `end` not included. */\n summaryOf(start = 0, end: number = this.size): Summary {\n return Tree.summaryOf(this.record, start, end);\n }\n\n /** This function gives the tree of the leaves of this tree, then the leaves of `other`. The two trees must have the same spec. */\n concat(other: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.concat(this.record, recordOf(other)));\n }\n\n /** This function splits the tree into its first `index` leaves and the other leaves. */\n splitAt(index: number): [SummaryTree<Leaf, Summary>, SummaryTree<Leaf, Summary>] {\n const [left, right] = Tree.splitAt(this.record, index);\n return [this.wrap(left), this.wrap(right)];\n }\n\n /**\n * This function splits the tree before the first leaf whose prefix summary satisfies the predicate. The prefix of a\n * leaf includes the leaf. The predicate must be monotone: after it is true for a prefix, it is true for each longer\n * prefix. When no prefix satisfies it, the right tree is empty.\n */\n split(predicate: (prefix: Summary) => boolean): [SummaryTree<Leaf, Summary>, SummaryTree<Leaf, Summary>] {\n const [left, right] = Tree.split(this.record, predicate);\n return [this.wrap(left), this.wrap(right)];\n }\n\n /**\n * This function finds the first leaf whose prefix summary satisfies a monotone predicate, as `split` does. It changes\n * nothing. It gives `undefined` when no prefix satisfies the predicate.\n */\n search(predicate: (prefix: Summary) => boolean): SummarySearch<Leaf, Summary> | undefined {\n return Tree.search(this.record, predicate);\n }\n\n /**\n * This function finds the leaf that holds a position of an additive key, and it calls no `combine`. The key must be\n * additive and not negative: `key(combine(a, b))` is `key(a) + key(b)`. The function descends by the key of each left\n * subtree and of each leaf, and subtracts it from the target. It gives the first leaf whose prefix key is more than\n * the target, or `undefined` when the target is not in `[0, key(summary))`.\n *\n * @example\n * // The leaf and the offset in it of the code unit at position 1000 of a rope\n * const at = rope.locate((s) => s.length, 1000);\n */\n locate(key: (summary: Summary) => number, target: number): SummaryLocation<Leaf> | undefined {\n return Tree.locate(this.record, key, target);\n }\n\n /** This function gives the tree of the leaves from `start` to `end`, with `end` not included. A negative index counts from the end. */\n slice(start = 0, end: number = this.size): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.slice(this.record, start, end));\n }\n\n /**\n * This function removes `deleteCount` leaves at `start` and puts the leaves of `inserted` there, as\n * `Array.prototype.splice` does. It gives the new tree, not the removed leaves.\n */\n splice(start: number, deleteCount: number = this.size, inserted: SummaryTree<Leaf, Summary> | Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.splice(this.record, start, deleteCount, recordOf(inserted)));\n }\n\n /** This function puts the leaves of `inserted` before the leaf at `index`. */\n insert(index: number, inserted: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.insert(this.record, index, recordOf(inserted)));\n }\n\n /** This function removes the leaves from `start` to `end`, with `end` not included. */\n remove(start: number, end: number = this.size): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.remove(this.record, start, end));\n }\n\n /**\n * This function replaces the leaf at an index. A negative index counts from the end, as `Array.prototype.with` does.\n * An index that is not in the tree changes nothing. It copies only the path to the leaf, and it does not call\n * `spec.merge`.\n */\n set(index: number, leaf: Leaf): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.set(this.record, index, leaf));\n }\n\n /** This function adds leaves after the last leaf. */\n append(...leaves: Leaf[]): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.append(this.record, ...leaves));\n }\n\n /** This function adds leaves before the first leaf. */\n prepend(...leaves: Leaf[]): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.prepend(this.record, ...leaves));\n }\n\n /** This function gives the leaves in their order. */\n [Symbol.iterator](): Iterator<Leaf> {\n return Tree.leaves(this.record);\n }\n\n /** This function gives the leaves in an array. */\n toArray(): Leaf[] {\n return Tree.toArray(this.record);\n }\n}\n\n/** This function gives the record of a tree, or the leaves when they are not a tree. */\nfunction recordOf<Leaf, Summary>(leaves: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTreeRecord<Leaf, Summary> | Iterable<Leaf> {\n return leaves instanceof SummaryTree ? leaves.record : leaves;\n}\n\n/**\n * This function makes a persistent tree of leaves with a summary of each part. Use the same `spec` object for each\n * tree that `concat` or `splice` joins.\n */\nexport function summaryTree<Leaf, Summary>(spec: SummarySpec<Leaf, Summary>, leaves: Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {\n return SummaryTree.of(spec, leaves);\n}\n\n/**\n * @internal This function examines the invariants of a tree: the AVL balance, the heights, the sizes and the\n * summaries. It gives a list of the faults, empty when there is no fault. The tests use it.\n */\nexport function summaryTreeFaults<Leaf, Summary>(\n tree: SummaryTree<Leaf, Summary> | SummaryTreeRecord<Leaf, Summary>,\n equal: (a: Summary, b: Summary) => boolean,\n): string[] {\n const { spec, root } = tree instanceof SummaryTree ? tree.record : tree;\n const { combine, empty } = spec.monoid;\n const heightOf = (n: SummaryNode<Leaf, Summary> | null): number => (n === null ? 0 : n.height);\n const sizeOf = (n: SummaryNode<Leaf, Summary> | null): number => (n === null ? 0 : n.size);\n const summaryOf = (n: SummaryNode<Leaf, Summary> | null): Summary => (n === null ? empty : n.summary);\n const faults: string[] = [];\n const visit = (node: SummaryNode<Leaf, Summary> | null, path: string): void => {\n if (node === null) return;\n visit(node.left, `${path}L`);\n visit(node.right, `${path}R`);\n const hl = heightOf(node.left);\n const hr = heightOf(node.right);\n if (Math.abs(hl - hr) > 1) faults.push(`${path}: balance ${hl - hr}`);\n if (node.height !== 1 + Math.max(hl, hr)) faults.push(`${path}: height ${node.height}`);\n if (node.size !== sizeOf(node.left) + 1 + sizeOf(node.right)) faults.push(`${path}: size ${node.size}`);\n const inner = combine(summaryOf(node.left), spec.measure(node.leaf));\n if (!equal(node.inner, inner)) faults.push(`${path}: inner`);\n if (!equal(node.summary, combine(inner, summaryOf(node.right)))) faults.push(`${path}: summary`);\n };\n visit(root, \"^\");\n return faults;\n}\n","/**\n * The check of a capacity, for each layer and class that has a maximum size.\n */\n\n/**\n * This function gives the capacity when it is a positive whole number. Otherwise it throws a\n * `RangeError`. A capacity of `NaN` makes a comparison `size >= capacity` always false, so a\n * structure with that capacity grows without a limit. A capacity of 0 or less, or a fraction,\n * has no clear meaning.\n *\n * @param capacity - The capacity to check.\n * @param owner - The name of the layer or class, for the message of the error.\n * @returns The same capacity.\n * @throws RangeError when the capacity is not a positive whole number.\n */\nexport function checkCapacity(capacity: number, owner: string): number {\n if (!Number.isSafeInteger(capacity) || capacity < 1) {\n throw new RangeError(`${owner}: the capacity must be a positive whole number, not ${String(capacity)}`);\n }\n return capacity;\n}\n","/**\n * Bounded behavior: this module enforces capacity limits on collections.\n *\n * This module wraps collections to prevent them from exceeding a maximum size.\n * This module gives various overflow policies to handle full collections.\n *\n * @example\n * const list = compose(\n * boundedList<number>({ capacity: 100, policy: 'drop-oldest' })\n * )(arrayList<number>())\n *\n * // Add 101 elements - first element will be dropped\n * for (let i = 0; i < 101; i++) {\n * list.add(i)\n * }\n */\n\nimport { checkCapacity } from \"../core/capacity.js\";\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue, Deque } from \"../interfaces/queue.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { removals, removalSource, type ElementRemoval, type MapRemoval } from \"../core/removals.js\";\nimport type { Collection } from \"../interfaces/collection.js\";\nimport type {\n OverflowPolicy,\n OverflowHandler,\n OverflowContext,\n} from \"../core/policies.js\";\n\n/**\n * Options for bounded behavior.\n */\nexport interface BoundedOptions<T> {\n /**\n * Maximum number of elements the collection can hold.\n */\n capacity: number;\n\n /**\n * Policy for handling overflow when collection is full.\n * @default 'throw'\n */\n policy?: OverflowPolicy;\n\n /**\n * Optional callback invoked when overflow occurs.\n * The behavior calls this function before it applies the policy.\n */\n onOverflow?: OverflowHandler<T>;\n}\n\n/**\n * Marker interface for bounded collections.\n */\nexport interface BoundedCollection {\n readonly capacity: number;\n readonly isFull: boolean;\n readonly remainingCapacity: number;\n}\n\n/**\n * This function makes a bounded List middleware.\n *\n * Intercepts add operations to enforce capacity limits.\n * This function supports multiple overflow policies.\n */\nexport function boundedList<T>(\n options: BoundedOptions<T>\n): Middleware<List<T>, List<T> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedList\");\n\n return (next: List<T>): List<T> & BoundedCollection => {\n const source = removalSource<ElementRemoval<T>>(next);\n // An unshift puts the element at the front, so drop-oldest drops the last element for it\n const handleOverflow = (element: T, dropFrom: \"first\" | \"last\" = \"first\"): void => {\n // Call overflow handler if provided\n if (onOverflow) {\n const context: OverflowContext<T> = {\n newElement: element,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n };\n onOverflow(context);\n }\n\n // Apply policy\n switch (policy) {\n case \"throw\":\n throw new Error(`List is full (capacity: ${capacity})`);\n\n case \"drop-oldest\":\n // Remove one element: the first, or the last for an unshift\n if (!next.isEmpty) {\n const value = dropFrom === \"last\" ? next.pop() : next.shift();\n source.emit({ value, end: dropFrom, reason: \"drop\" });\n }\n break;\n\n case \"drop-newest\":\n // Don't add the new element (do nothing)\n return;\n\n case \"reject\":\n // Silently reject (return false for add operations)\n return;\n\n case \"grow\":\n // Allow growth (do nothing, element will be added)\n return;\n\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n // After drop-oldest removed the first element, an index of the caller is one place lower\n const shifted = (index: number): number => (policy === \"drop-oldest\" ? Math.max(0, index - 1) : index);\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n // Capacity property\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") {\n return capacity;\n }\n\n // isFull property\n if (prop === \"isFull\") {\n return target.size >= capacity;\n }\n\n // remainingCapacity property\n if (prop === \"remainingCapacity\") {\n return Math.max(0, capacity - target.size);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n // Intercept methods that add elements\n if (typeof value === \"function\") {\n switch (prop) {\n case \"add\":\n return function (element: T): boolean {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return false;\n }\n }\n return (value as Function).call(target, element);\n };\n\n case \"push\":\n return function (element: T): void {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return;\n }\n }\n (value as Function).call(target, element);\n };\n\n case \"unshift\":\n return function (element: T): void {\n if (target.size >= capacity && policy !== \"grow\") {\n // One element goes: the last one (before, the first and the last went: audit pass 2)\n handleOverflow(element, \"last\");\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return;\n }\n }\n (value as Function).call(target, element);\n };\n\n case \"insert\":\n return function (index: number, element: T): void {\n let at = index;\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return;\n }\n at = shifted(at);\n }\n (value as Function).call(target, at, element);\n };\n\n case \"addAll\":\n case \"insertAll\":\n return function (...args: any[]): boolean {\n const elements = args[args.length - 1] as Iterable<T>;\n const elementsArray = Array.from(elements);\n\n // Check if adding all elements would exceed capacity\n if (target.size + elementsArray.length > capacity && policy !== \"grow\") {\n // Add elements one by one with overflow handling. An insert keeps the order of\n // the elements, at an index that follows each drop.\n let added = false;\n let at = args[0] as number;\n for (const element of elementsArray) {\n if (target.size >= capacity) {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n break;\n }\n at = shifted(at);\n }\n if (prop === \"addAll\") {\n target.add(element);\n } else {\n target.insert(at, element);\n at++;\n }\n added = true;\n }\n return added;\n }\n\n return (value as Function).apply(target, args);\n };\n }\n }\n\n return value;\n },\n }) as List<T> & BoundedCollection;\n };\n}\n\n/**\n * This function adds each element with `add`, one after the other, until `add` refuses one.\n * It gives true when one element goes in. A throw of `add` stops it, and the earlier elements stay.\n */\nfunction addEach<T>(elements: Iterable<T>, add: (element: T) => boolean): boolean {\n let added = false;\n for (const element of Array.from(elements)) {\n if (!add(element)) break;\n added = true;\n }\n return added;\n}\n\n/**\n * This function makes a bounded Queue middleware.\n */\nexport function boundedQueue<T>(\n options: BoundedOptions<T>\n): Middleware<Queue<T>, Queue<T> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedQueue\");\n\n return (next: Queue<T>): Queue<T> & BoundedCollection => {\n const source = removalSource<ElementRemoval<T>>(next);\n const handleOverflow = (element: T): void => {\n if (onOverflow) {\n const context: OverflowContext<T> = {\n newElement: element,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n };\n onOverflow(context);\n }\n\n switch (policy) {\n case \"throw\":\n throw new Error(`Queue is full (capacity: ${capacity})`);\n case \"drop-oldest\":\n if (!next.isEmpty) {\n source.emit({ value: next.poll() as T, end: \"first\", reason: \"drop\" });\n }\n break;\n case \"drop-newest\":\n case \"reject\":\n return;\n case \"grow\":\n return;\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") return capacity;\n if (prop === \"isFull\") return target.size >= capacity;\n if (prop === \"remainingCapacity\") return Math.max(0, capacity - target.size);\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"offer\":\n case \"enqueue\":\n case \"add\":\n return function (element: T): boolean {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return false;\n }\n }\n return (value as Function).call(target, element);\n };\n\n // The base addAll goes past the bound, so each element goes through add of this proxy (C10)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => (receiver as Queue<T>).add(element));\n };\n }\n }\n\n return value;\n },\n }) as Queue<T> & BoundedCollection;\n };\n}\n\n/**\n * This function makes a bounded Deque middleware.\n */\nexport function boundedDeque<T>(\n options: BoundedOptions<T>\n): Middleware<Deque<T>, Deque<T> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedDeque\");\n\n return (next: Deque<T>): Deque<T> & BoundedCollection => {\n const source = removalSource<ElementRemoval<T>>(next);\n // An insert at the front drops the last element, as unshift of boundedList does (C10)\n const handleOverflow = (element: T, dropFrom: \"first\" | \"last\"): void => {\n if (onOverflow) {\n const context: OverflowContext<T> = {\n newElement: element,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n };\n onOverflow(context);\n }\n\n switch (policy) {\n case \"throw\":\n throw new Error(`Deque is full (capacity: ${capacity})`);\n case \"drop-oldest\":\n if (!next.isEmpty) {\n const value = dropFrom === \"last\" ? next.removeLast() : next.removeFirst();\n source.emit({ value, end: dropFrom, reason: \"drop\" });\n }\n break;\n case \"drop-newest\":\n case \"reject\":\n return;\n case \"grow\":\n return;\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") return capacity;\n if (prop === \"isFull\") return target.size >= capacity;\n if (prop === \"remainingCapacity\") return Math.max(0, capacity - target.size);\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"addFirst\":\n case \"addLast\":\n case \"offerFirst\":\n case \"offerLast\":\n case \"push\":\n case \"offer\":\n case \"add\":\n return function (element: T): any {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element, prop === \"addFirst\" || prop === \"offerFirst\" ? \"last\" : \"first\");\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return prop.startsWith(\"offer\") || prop === \"add\" ? false : undefined;\n }\n }\n return (value as Function).call(target, element);\n };\n\n // The base addAll goes past the bound, so each element goes through add of this proxy (C10)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => (receiver as Deque<T>).add(element));\n };\n }\n }\n\n return value;\n },\n }) as Deque<T> & BoundedCollection;\n };\n}\n\n/**\n * This function makes a bounded Map middleware.\n */\nexport function boundedMap<K, V>(\n options: Omit<BoundedOptions<V>, \"onOverflow\"> & {\n onOverflow?: (context: Omit<OverflowContext<V>, \"newElement\"> & { key: K; value: V }) => void;\n }\n): Middleware<MapLike<K, V>, MapLike<K, V> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedMap\");\n\n return (next: MapLike<K, V>): MapLike<K, V> & BoundedCollection => {\n let insertionOrder: K[] = []; // Track insertion order for drop-oldest\n // A removal below (for example an eviction of lruMap) takes its key out of the order\n const source = removalSource<MapRemoval<K, V>>(next, ({ key }) => {\n insertionOrder = insertionOrder.filter((k) => !next.keyEq(k, key));\n });\n\n const handleOverflow = (key: K, value: V): void => {\n if (onOverflow) {\n onOverflow({\n key,\n value,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n });\n }\n\n switch (policy) {\n case \"throw\":\n throw new Error(`Map is full (capacity: ${capacity})`);\n case \"drop-oldest\":\n // Remove oldest key\n // The removal channel below keeps the order exact. A layer below with no channel can remove a key\n // without this layer seeing it, so a drop skips each key that is gone.\n while (insertionOrder.length > 0) {\n const oldestKey = insertionOrder.shift()!;\n if (!next.has(oldestKey)) continue;\n const value = next.get(oldestKey);\n next.delete(oldestKey);\n source.emit({ key: oldestKey, value, reason: \"drop\" });\n break;\n }\n break;\n case \"drop-newest\":\n case \"reject\":\n return;\n case \"grow\":\n return;\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") return capacity;\n if (prop === \"isFull\") return target.size >= capacity;\n if (prop === \"remainingCapacity\") return Math.max(0, capacity - target.size);\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"set\":\n return function (key: K, val: V): V | undefined {\n const hadKey = target.has(key);\n\n if (!hadKey && target.size >= capacity && policy !== \"grow\") {\n handleOverflow(key, val);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return undefined;\n }\n }\n\n const result = (value as Function).call(target, key, val);\n\n // Track insertion order\n if (!hadKey) {\n insertionOrder.push(key);\n }\n\n return result;\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n const result = (value as Function).call(target, key);\n // Remove from insertion order tracking\n insertionOrder = insertionOrder.filter((k) => !target.keyEq(k, key));\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n insertionOrder = [];\n };\n }\n }\n\n return value;\n },\n }) as MapLike<K, V> & BoundedCollection;\n };\n}\n\n/**\n * Generic bounded collection middleware.\n * Works with any collection type.\n */\nexport function bounded<C extends Collection<any>>(\n options: BoundedOptions<any>\n): Middleware<C, C & BoundedCollection> {\n return boundedList(options) as any;\n}\n","/**\n * Readonly behavior: this module makes immutable views of collections.\n *\n * This module wraps collections to prevent modifications by throwing errors\n * on any mutation try. Mirrors Java's Collections.unmodifiable*() methods.\n *\n * @example\n * const list = compose(\n * readonlyList()\n * )(arrayList([1, 2, 3]))\n *\n * list.get(0) // OK: 1\n * list.add(4) // Error: Cannot modify readonly list\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { ReadonlyList } from \"../interfaces/list.js\";\nimport type { ReadonlyQueue } from \"../interfaces/queue.js\";\nimport type { ReadonlyMapLike } from \"../interfaces/map.js\";\nimport type { ReadonlyCollection } from \"../interfaces/collection.js\";\n\n/**\n * Options for readonly behavior.\n */\nexport interface ReadonlyOptions {\n /**\n * Custom error message to throw on mutation tries.\n * @default 'Cannot modify readonly collection'\n */\n errorMessage?: string;\n}\n\n/**\n * This set holds the names of the methods that mutate collections.\n */\nconst MUTATING_METHODS = new Set([\n // Collection mutations\n \"add\",\n \"addAll\",\n \"remove\",\n \"removeAll\",\n \"retainAll\",\n \"clear\",\n\n // List mutations\n \"set\",\n \"insert\",\n \"insertAll\",\n \"removeAt\",\n \"removeRange\",\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"sort\",\n \"reverse\",\n\n // Queue/Deque mutations\n \"offer\",\n \"offerFirst\",\n \"offerLast\",\n \"poll\",\n \"pollFirst\",\n \"pollLast\",\n \"enqueue\",\n \"dequeue\",\n \"addFirst\",\n \"addLast\",\n \"removeFirst\",\n \"removeLast\",\n\n // Map mutations\n \"set\",\n \"setIfAbsent\",\n \"forcePut\",\n \"pollFirstEntry\",\n \"pollLastEntry\",\n \"delete\",\n \"deleteEntry\",\n \"replace\",\n \"replaceEntry\",\n \"computeIfAbsent\",\n \"computeIfPresent\",\n \"compute\",\n \"merge\",\n \"putAll\",\n\n // Queue changes that give undefined on an empty queue (C27: a readonly view removed an element)\n \"pollOrUndefined\",\n\n // The removal by a test of LRUCache (C31: a readonly view of an LRU cache emptied it)\n \"deleteWhere\",\n\n // The internal changes of the structures of this package. TypeScript marks them private, but a call at run\n // time reaches them. `readonly.test.ts` puts each method of each structure in the reads or in this list.\n \"ensureCapacity\",\n \"trimToSize\",\n \"grow\",\n \"resize\",\n \"removeAtOffset\",\n \"unlinkNode\",\n \"heapify\",\n \"bubbleUp\",\n \"bubbleDown\",\n \"addToEnd\",\n \"moveToEnd\",\n \"removeFromBucket\",\n \"removeFromList\",\n \"deleteNode\",\n \"fixAfterInsertion\",\n \"fixAfterDeletion\",\n \"rotateLeft\",\n \"rotateRight\",\n \"moveToHead\",\n \"removeNode\",\n \"evictLRU\",\n]);\n\n/** Methods that return a view of the collection: the view is readonly too. */\nconst VIEW_METHODS = new Set([\n \"subList\",\n \"subMap\",\n \"subSet\",\n \"headMap\",\n \"tailMap\",\n \"headSet\",\n \"tailSet\",\n \"descendingMap\",\n \"descendingSet\",\n \"inverse\",\n]);\n\n/**\n * This function makes a readonly middleware for any collection type.\n */\nfunction createReadonly<C extends object>(\n errorMessage: string = \"Cannot modify readonly collection\"\n): Middleware<C> {\n return (next: C): C => {\n // The read methods, bound to the collection: one function for each name\n const bound = new Map<PropertyKey, { value: Function; method: Function }>();\n return new Proxy(next, {\n get(target, prop) {\n // A read runs on the collection itself, not on the proxy: a read that changes internal\n // state (a LinkedHashMap with accessOrder moves the entry) does not hit the set trap\n const value = Reflect.get(target, prop, target);\n\n // Block mutating methods\n if (typeof prop === \"string\" && MUTATING_METHODS.has(prop)) {\n if (typeof value === \"function\") {\n return () => {\n throw new Error(errorMessage);\n };\n }\n }\n\n // A view (a sublist, a submap, a head or tail set, a descending map) is readonly too.\n // Before, only subList and subMap were wrapped, and setIfAbsent, pollFirstEntry and\n // pollLastEntry were not blocked (BUGS-2026-07 L14).\n if (typeof value === \"function\" && typeof prop === \"string\" && VIEW_METHODS.has(prop)) {\n return function (this: any, ...args: any[]) {\n const result = value.apply(target, args);\n // Recursively apply readonly to the result\n return createReadonly<typeof result>(errorMessage)(result);\n };\n }\n\n if (typeof value === \"function\") {\n const known = bound.get(prop);\n if (known !== undefined && known.value === value) return known.method;\n const method = (value as Function).bind(target) as Function;\n bound.set(prop, { value, method });\n return method;\n }\n\n return value;\n },\n\n set(_target, _prop, _value, _receiver) {\n // Block property assignments\n throw new Error(errorMessage);\n },\n\n deleteProperty(_target, _prop) {\n // Block property deletions\n throw new Error(errorMessage);\n },\n });\n };\n}\n\n/**\n * This function makes a readonly List middleware.\n *\n * All mutation methods will throw an error.\n * Read operations work normally.\n *\n * @example\n * const readonlyNumbers = compose(\n * readonlyList()\n * )(arrayList([1, 2, 3]))\n */\nexport function readonlyList<T>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyList<T>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly list\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * This function makes a readonly Queue middleware.\n */\nexport function readonlyQueue<T>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyQueue<T>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly queue\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * This function makes a readonly Map middleware.\n */\nexport function readonlyMap<K, V>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyMapLike<K, V>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly map\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * This function makes a readonly Collection middleware.\n *\n * Generic version that works with any collection type.\n */\nexport function readonlyCollection<T>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyCollection<T>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly collection\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * Generic readonly middleware.\n * Alias for readonlyCollection.\n */\nexport function readonly<C extends object>(\n options: ReadonlyOptions = {}\n): Middleware<C> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly collection\";\n return createReadonly<C>(errorMessage);\n}\n\n/**\n * Alias for Java compatibility: unmodifiableList\n */\nexport const unmodifiableList : typeof readonlyList = readonlyList;\n\n/**\n * Alias for Java compatibility: unmodifiableMap\n */\nexport const unmodifiableMap : typeof readonlyMap = readonlyMap;\n\n/**\n * Alias for Java compatibility: unmodifiableCollection\n */\nexport const unmodifiableCollection : typeof readonlyCollection = readonlyCollection;\n","/**\n * The safe middleware. Each operation that throws on a missing element has a safe form in the property `safe`. The safe\n * form gives an `Optional` or a `Result` of `@mark1russell7/optional`, and does not throw.\n *\n * @example\n * import { isSome } from \"@mark1russell7/optional\";\n *\n * const list = compose(safeList<number>())(arrayList<number>());\n * const value = list.safe.get(10); // an Optional<number>, not an exception\n * if (isSome(value)) console.log(value.value);\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue, Deque } from \"../interfaces/queue.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { none, some, toOptional, tryCatch, type Optional, type Result } from \"@mark1russell7/optional\";\n\n/**\n * Safe operations for List.\n */\nexport interface SafeListOperations<T> {\n /**\n * This method gives the element at an index, as an optional.\n */\n get(index: number): Optional<T>;\n\n /**\n * This method sets the element at an index. It gives a Result with the old value or an error.\n */\n set(index: number, element: T): Result<T, string>;\n\n /**\n * This method removes the element at an index. It gives a Result with the removed value or an error.\n */\n removeAt(index: number): Result<T, string>;\n\n /**\n * This method gives the first element, as an optional.\n */\n first(): Optional<T>;\n\n /**\n * This method gives the last element, as an optional.\n */\n last(): Optional<T>;\n\n /**\n * Pop element, as an optional.\n */\n pop(): Optional<T>;\n\n /**\n * Shift element, as an optional.\n */\n shift(): Optional<T>;\n}\n\n/**\n * Safe operations for Queue.\n */\nexport interface SafeQueueOperations<T> {\n /**\n * This method gives the head element as an optional, and does not remove it.\n */\n peek(): Optional<T>;\n\n /**\n * This method removes the head element and gives it as an optional.\n */\n poll(): Optional<T>;\n\n /**\n * This method dequeues the head element and gives it as an optional.\n */\n dequeue(): Optional<T>;\n}\n\n/**\n * Safe operations for Deque.\n */\nexport interface SafeDequeOperations<T> extends SafeQueueOperations<T> {\n /**\n * This method gives the first element as an optional, and does not remove it.\n */\n peekFirst(): Optional<T>;\n\n /**\n * This method gives the last element as an optional, and does not remove it.\n */\n peekLast(): Optional<T>;\n\n /**\n * This method removes the first element and gives it as an optional.\n */\n pollFirst(): Optional<T>;\n\n /**\n * This method removes the last element and gives it as an optional.\n */\n pollLast(): Optional<T>;\n\n /**\n * This method pops the top element and gives it as an optional.\n */\n pop(): Optional<T>;\n}\n\n/**\n * Safe operations for Map.\n */\nexport interface SafeMapOperations<K, V> {\n /**\n * This method gives the value of a key, as an optional.\n */\n get(key: K): Optional<V>;\n\n /**\n * This method sets the value of a key. It gives a Result with the old value or a success.\n */\n set(key: K, value: V): Result<V | undefined, string>;\n\n /**\n * This method deletes a key. It gives a Result with the deleted value or an error.\n */\n delete(key: K): Result<V | undefined, string>;\n}\n\n/**\n * This function makes a safe List middleware.\n *\n * This function exposes a `safe` property with Optional/Result-based operations.\n */\nexport function safeList<T>(): Middleware<\n List<T>,\n List<T> & { safe: SafeListOperations<T> }\n> {\n return (next: List<T>): List<T> & { safe: SafeListOperations<T> } => {\n const safe: SafeListOperations<T> = {\n get(index: number): Optional<T> {\n return toOptional(tryCatch(() => next.get(index)));\n },\n\n set(index: number, element: T): Result<T, string> {\n return tryCatch(\n () => next.set(index, element),\n (error) => String(error)\n );\n },\n\n removeAt(index: number): Result<T, string> {\n return tryCatch(\n () => next.removeAt(index),\n (error) => String(error)\n );\n },\n\n first(): Optional<T> {\n return next.isEmpty ? none : some(next.first());\n },\n\n last(): Optional<T> {\n return next.isEmpty ? none : some(next.last());\n },\n\n pop(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.pop()));\n },\n\n shift(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.shift()));\n },\n };\n\n // Extend next with safe property\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * This function makes a safe Queue middleware.\n */\nexport function safeQueue<T>(): Middleware<\n Queue<T>,\n Queue<T> & { safe: SafeQueueOperations<T> }\n> {\n return (next: Queue<T>): Queue<T> & { safe: SafeQueueOperations<T> } => {\n const safe: SafeQueueOperations<T> = {\n peek(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.peek()));\n },\n\n poll(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.poll()));\n },\n\n dequeue(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.dequeue()));\n },\n };\n\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * This function makes a safe Deque middleware.\n */\nexport function safeDeque<T>(): Middleware<\n Deque<T>,\n Deque<T> & { safe: SafeDequeOperations<T> }\n> {\n return (next: Deque<T>): Deque<T> & { safe: SafeDequeOperations<T> } => {\n const safe: SafeDequeOperations<T> = {\n peek(): Optional<T> {\n return next.isEmpty ? none : some(next.peekFirst());\n },\n\n poll(): Optional<T> {\n // One poll: before, the test and the result each called pollFirst(), so poll() removed\n // two elements and returned the second (BUGS-2026-07 L12)\n if (next.isEmpty) return none;\n return some(next.pollFirst() as T);\n },\n\n dequeue(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.dequeue()));\n },\n\n peekFirst(): Optional<T> {\n return next.isEmpty ? none : some(next.peekFirst());\n },\n\n peekLast(): Optional<T> {\n return next.isEmpty ? none : some(next.peekLast());\n },\n\n pollFirst(): Optional<T> {\n const result = next.pollFirst();\n return result !== undefined ? some(result) : none;\n },\n\n pollLast(): Optional<T> {\n const result = next.pollLast();\n return result !== undefined ? some(result) : none;\n },\n\n pop(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.pop()));\n },\n };\n\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * This function makes a safe Map middleware.\n */\nexport function safeMap<K, V>(): Middleware<\n MapLike<K, V>,\n MapLike<K, V> & { safe: SafeMapOperations<K, V> }\n> {\n return (\n next: MapLike<K, V>\n ): MapLike<K, V> & { safe: SafeMapOperations<K, V> } => {\n const safe: SafeMapOperations<K, V> = {\n get(key: K): Optional<V> {\n return next.has(key) ? some(next.get(key)) : none;\n },\n\n set(key: K, value: V): Result<V | undefined, string> {\n return tryCatch(\n () => next.set(key, value),\n (error) => String(error)\n );\n },\n\n delete(key: K): Result<V | undefined, string> {\n return tryCatch(\n () => next.delete(key),\n (error) => String(error)\n );\n },\n };\n\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * Generic safe middleware that works with any collection.\n */\nexport function safe<C extends object>(): Middleware<C> {\n // Return as-is for now; specialized versions handle specific types\n return (next: C): C => next;\n}\n","/**\n * Composite map methods built on `has`, `get`, `set` and `delete`.\n *\n * A map behavior (lruMap, ttlMap) intercepts the primitive methods. It gives these\n * implementations for the composite methods, bound to the behavior's own proxy.\n * Thus a call like `setIfAbsent` goes through the behavior's `set` and keeps its rules:\n * capacity and recency for LRU, expiry for TTL. (BUGS-2026-07 L13: the composite methods\n * went straight to the map below, so they bypassed the behavior.)\n *\n * The semantics follow HashMap. One difference: `replaceEntry` and `deleteEntry` compare\n * values with Object.is, not with a map's custom value equality.\n */\n\nimport type { Entry, MapLike } from \"../interfaces/map.js\";\n\ntype AnyFn = (...args: never[]) => unknown;\n\nexport function compositeMapMethod<K, V>(map: MapLike<K, V>, name: PropertyKey): AnyFn | undefined {\n switch (name) {\n case \"setIfAbsent\":\n return ((key: K, value: V): V => {\n if (map.has(key)) return map.get(key);\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"replace\":\n return ((key: K, value: V): V | undefined => (map.has(key) ? map.set(key, value) : undefined)) as AnyFn;\n\n case \"replaceEntry\":\n return ((key: K, oldValue: V, newValue: V): boolean => {\n if (!map.has(key) || !Object.is(map.get(key), oldValue)) return false;\n map.set(key, newValue);\n return true;\n }) as AnyFn;\n\n case \"deleteEntry\":\n return ((key: K, value: V): boolean => {\n if (!map.has(key) || !Object.is(map.get(key), value)) return false;\n map.delete(key);\n return true;\n }) as AnyFn;\n\n case \"computeIfAbsent\":\n return ((key: K, mappingFunction: (key: K) => V): V => {\n if (map.has(key)) return map.get(key);\n const value = mappingFunction(key);\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"computeIfPresent\":\n return ((key: K, remapping: (key: K, value: V) => V | undefined): V | undefined => {\n if (!map.has(key)) return undefined;\n const value = remapping(key, map.get(key));\n if (value === undefined) {\n map.delete(key);\n return undefined;\n }\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"compute\":\n return ((key: K, remapping: (key: K, value: V | undefined) => V | undefined): V | undefined => {\n const present = map.has(key);\n const value = remapping(key, present ? map.get(key) : undefined);\n if (value === undefined) {\n if (present) map.delete(key);\n return undefined;\n }\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"merge\":\n return ((key: K, value: V, remapping: (oldValue: V, newValue: V) => V | undefined): V | undefined => {\n if (!map.has(key)) {\n map.set(key, value);\n return value;\n }\n const merged = remapping(map.get(key), value);\n if (merged === undefined) {\n map.delete(key);\n return undefined;\n }\n map.set(key, merged);\n return merged;\n }) as AnyFn;\n\n case \"putAll\":\n return ((other: Iterable<Entry<K, V>>): void => {\n for (const entry of other) {\n map.set(entry.key, entry.value);\n }\n }) as AnyFn;\n }\n return undefined;\n}\n","/**\n * Evented behavior: this module emits typed events on collection mutations.\n *\n * This module wraps collections to emit events whenever elements are added, removed,\n * or the collection is cleared. This module enables reactive programming patterns.\n *\n * @example\n * const list = compose(\n * eventedList<number>()\n * )(arrayList<number>())\n *\n * list.on('add', ({ value, index }) => {\n * console.log(`Added ${value} at index ${index}`)\n * })\n *\n * list.add(42) // Triggers 'add' event\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue, Deque } from \"../interfaces/queue.js\";\nimport type { Entry, MapLike } from \"../interfaces/map.js\";\nimport type { Collection } from \"../interfaces/collection.js\";\nimport { Emitter, type Unsubscribe } from \"../core/events.js\";\nimport { removalsOf, type ElementRemoval, type MapRemoval, type RemovalReason } from \"../core/removals.js\";\nimport { compositeMapMethod } from \"./composite.js\";\n\n/** The number of removals that a layer heard from the layers below it, and the number from the first end. */\ninterface Heard {\n all: number;\n first: number;\n}\n\n/**\n * This function gives each removal below `next` to `listener` and counts the removals.\n * With the counts, a layer tells a refused add (the size did not grow) from an add that caused a drop.\n */\nfunction hear<R extends ElementRemoval<unknown> | MapRemoval<unknown, unknown>>(next: object, listener: (removal: R) => void): Heard {\n const heard: Heard = { all: 0, first: 0 };\n removalsOf<R>(next)?.on((removal) => {\n heard.all++;\n if (\"end\" in removal && removal.end === \"first\") heard.first++;\n listener(removal);\n });\n return heard;\n}\n\n/** This function tells if a call added an element: the size grew, after the removals of the layers below. */\nconst added = (size: number, sizeBefore: number, heard: Heard, heardBefore: number): boolean =>\n size - sizeBefore + heard.all - heardBefore > 0;\n\n/**\n * This function gives the removals that change `before` to `after`, in the order of a replay.\n * Each index is the place of the value at the time of its removal. It gives undefined when `after` is not in the order of `before`.\n */\nfunction removalsInOrder<T>(before: readonly T[], after: readonly T[]): { value: T; index: number }[] | undefined {\n const removed: { value: T; index: number }[] = [];\n let kept = 0;\n for (const value of before) {\n if (kept < after.length && Object.is(value, after[kept])) kept++;\n else removed.push({ value, index: kept });\n }\n return kept === after.length ? removed : undefined;\n}\n\n/** This function gives the values of `before` that are not in `after`, with each copy counted. The order does not matter. */\nfunction removedValues<T>(before: readonly T[], after: readonly T[]): T[] {\n const left = new Map<T, number>();\n for (const value of after) left.set(value, (left.get(value) ?? 0) + 1);\n const removed: T[] = [];\n for (const value of before) {\n const count = left.get(value) ?? 0;\n if (count > 0) left.set(value, count - 1);\n else removed.push(value);\n }\n return removed;\n}\n\n/**\n * This function wraps a bulk removal (removeAll, retainAll, removeRange) of the collection below.\n * The base does the removal with its own equality, and `report` gets the contents before and after it.\n */\nfunction bulkRemoval<T>(\n target: { readonly size: number; toArray(): T[] },\n method: Function,\n report: (before: T[], after: T[]) => void,\n): (...args: unknown[]) => unknown {\n return function (...args: unknown[]): unknown {\n const before = target.toArray();\n const result = method.apply(target, args);\n if (target.size !== before.length) report(before, target.toArray());\n return result;\n };\n}\n\n/**\n * This function adds each element with `add` of the layer, one after the other.\n * Thus each element gives its own event, with the rules of a single add. It gives true when one element goes in.\n */\nfunction addEach<T>(elements: Iterable<T>, add: (element: T) => boolean): boolean {\n let changed = false;\n for (const element of Array.from(elements)) {\n if (add(element)) changed = true;\n }\n return changed;\n}\n\n// ============================================================================\n// Event type definitions\n// ============================================================================\n\n/**\n * Events emitted by List collections.\n */\nexport interface ListEvents<T> {\n /** Element was added */\n add: { value: T; index?: number };\n /** Element was removed. A removal by a layer below (a drop) has a `reason`. */\n remove: { value: T; index?: number; reason?: RemovalReason };\n /** Element was replaced */\n set: { oldValue: T; newValue: T; index: number };\n /** Collection was cleared */\n clear: {};\n /** Collection was sorted */\n sort: {};\n /** Collection was reversed */\n reverse: {};\n}\n\n/**\n * Events emitted by Queue collections.\n */\nexport interface QueueEvents<T> {\n /** Element was added to queue */\n enqueue: { value: T };\n /** Element was removed from queue. A removal by a layer below (a drop) has a `reason`. */\n dequeue: { value: T; reason?: RemovalReason };\n /** An element left from a place that is not the head: `remove`, `removeAll` or `retainAll`. */\n remove: { value: T };\n /** Collection was cleared */\n clear: {};\n}\n\n/**\n * Events emitted by Deque collections.\n */\nexport interface DequeEvents<T> {\n /** Element was added to front */\n addFirst: { value: T };\n /** Element was added to back */\n addLast: { value: T };\n /** Element was removed from front. A removal by a layer below (a drop) has a `reason`. */\n removeFirst: { value: T; reason?: RemovalReason };\n /** Element was removed from back. A removal by a layer below (a drop) has a `reason`. */\n removeLast: { value: T; reason?: RemovalReason };\n /** An element left from `index`, not with a method of an end: `remove`, `removeAll` or `retainAll`. */\n remove: { value: T; index: number };\n /** Collection was cleared */\n clear: {};\n}\n\n/**\n * Events emitted by Map collections.\n */\nexport interface MapEvents<K, V> {\n /** Key-value pair was set */\n set: { key: K; value: V; oldValue?: V };\n /** Key was deleted. A removal by a layer below (a drop, an eviction or an expiry) has a `reason`. */\n delete: { key: K; value: V; reason?: RemovalReason };\n /** Collection was cleared */\n clear: {};\n}\n\n/**\n * Generic collection events.\n */\nexport interface CollectionEvents<T> {\n /** Element was added */\n add: { value: T };\n /** Element was removed. A removal by a layer below has a `reason`. */\n remove: { value: T; reason?: RemovalReason };\n /** Collection was cleared */\n clear: {};\n}\n\n// ============================================================================\n// Evented middleware implementations\n// ============================================================================\n\n/**\n * This function makes an evented List middleware.\n *\n * This function emits events for add, remove, set, clear, sort, and reverse operations.\n */\nexport function eventedList<T>(): Middleware<\n List<T>,\n List<T> & {\n on<E extends keyof ListEvents<T>>(\n event: E,\n listener: (payload: ListEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: List<T>) => {\n const emitter = new Emitter<ListEvents<T>>();\n // A removal from the last end left the index that is now the size\n const heard = hear<ElementRemoval<T>>(next, ({ value, end, reason }) =>\n emitter.emit(\"remove\", end === undefined ? { value, reason } : { value, index: end === \"first\" ? 0 : next.size, reason }),\n );\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n // Expose event subscription\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n // A layer below can refuse the element (reject, drop-newest): then no event\n case \"add\":\n case \"push\":\n return function (element: T): any {\n const size = target.size;\n const all = heard.all;\n const result = (value as Function).call(target, element);\n if (added(target.size, size, heard, all)) emitter.emit(\"add\", { value: element });\n return result;\n };\n\n case \"unshift\":\n return function (element: T): void {\n const size = target.size;\n const all = heard.all;\n (value as Function).call(target, element);\n if (added(target.size, size, heard, all)) emitter.emit(\"add\", { value: element, index: 0 });\n };\n\n case \"insert\":\n return function (index: number, element: T): void {\n const size = target.size;\n const all = heard.all;\n const first = heard.first;\n (value as Function).call(target, index, element);\n if (!added(target.size, size, heard, all)) return;\n // A drop of the first element below moved each later index one place lower\n emitter.emit(\"add\", { value: element, index: heard.first > first ? Math.max(0, index - 1) : index });\n };\n\n case \"set\":\n return function (index: number, element: T): T {\n const oldValue = (value as Function).call(target, index, element);\n emitter.emit(\"set\", { oldValue, newValue: element, index });\n return oldValue;\n };\n\n case \"remove\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n emitter.emit(\"remove\", { value: element });\n }\n return result;\n };\n\n case \"removeAt\":\n return function (index: number): T {\n const removed = (value as Function).call(target, index);\n emitter.emit(\"remove\", { value: removed, index });\n return removed;\n };\n\n case \"pop\":\n return function (): T {\n const removed = (value as Function).call(target);\n // The last element had the index that is now the size\n emitter.emit(\"remove\", { value: removed, index: target.size });\n return removed;\n };\n\n case \"shift\":\n return function (): T {\n const removed = (value as Function).call(target);\n emitter.emit(\"remove\", { value: removed, index: 0 });\n return removed;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => {\n const size = target.size;\n const all = heard.all;\n (receiver as List<T>).add(element);\n return added(target.size, size, heard, all);\n });\n };\n\n case \"insertAll\":\n return function (index: number, elements: Iterable<T>): boolean {\n let at = index;\n return addEach(elements, (element) => {\n const size = target.size;\n const all = heard.all;\n const first = heard.first;\n (receiver as List<T>).insert(at, element);\n const wentIn = added(target.size, size, heard, all);\n // A drop of the first element below moved the place one lower. The next element goes after a new one.\n at = Math.min(target.size, Math.max(0, at - (heard.first - first)) + (wentIn ? 1 : 0));\n return wentIn;\n });\n };\n\n case \"removeAll\":\n case \"retainAll\":\n case \"removeRange\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n const removed = removalsInOrder(before, after);\n if (removed) {\n for (const removal of removed) emitter.emit(\"remove\", removal);\n return;\n }\n // A base that changed the order of the rest: a clear and the adds give the same contents\n emitter.emit(\"clear\", {});\n after.forEach((element, at) => emitter.emit(\"add\", { value: element, index: at }));\n });\n\n case \"sort\":\n return function (...args: any[]): void {\n (value as Function).apply(target, args);\n emitter.emit(\"sort\", {});\n };\n\n case \"reverse\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"reverse\", {});\n };\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * This function makes an evented Queue middleware.\n */\nexport function eventedQueue<T>(): Middleware<\n Queue<T>,\n Queue<T> & {\n on<E extends keyof QueueEvents<T>>(\n event: E,\n listener: (payload: QueueEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: Queue<T>) => {\n const emitter = new Emitter<QueueEvents<T>>();\n hear<ElementRemoval<T>>(next, ({ value, reason }) => emitter.emit(\"dequeue\", { value, reason }));\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"offer\":\n case \"enqueue\":\n case \"add\":\n return function (element: T): any {\n const result = (value as Function).call(target, element);\n if (result !== false) {\n emitter.emit(\"enqueue\", { value: element });\n }\n return result;\n };\n\n case \"poll\":\n case \"dequeue\":\n return function (): T {\n const removed = (value as Function).call(target);\n emitter.emit(\"dequeue\", { value: removed });\n return removed;\n };\n\n case \"pollOrUndefined\":\n return function (): T | undefined {\n const size = target.size;\n const removed = (value as Function).call(target);\n if (target.size < size) emitter.emit(\"dequeue\", { value: removed });\n return removed;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => (receiver as Queue<T>).add(element) !== false);\n };\n\n case \"remove\":\n case \"removeAll\":\n case \"retainAll\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n for (const removed of removedValues(before, after)) emitter.emit(\"remove\", { value: removed });\n });\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * This function makes an evented Deque middleware.\n */\nexport function eventedDeque<T>(): Middleware<\n Deque<T>,\n Deque<T> & {\n on<E extends keyof DequeEvents<T>>(\n event: E,\n listener: (payload: DequeEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: Deque<T>) => {\n const emitter = new Emitter<DequeEvents<T>>();\n const heard = hear<ElementRemoval<T>>(next, ({ value, end, reason }) =>\n emitter.emit(end === \"last\" ? \"removeLast\" : \"removeFirst\", { value, reason }),\n );\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n // push of a deque adds at the end (see Deque.push). A layer below can refuse the element.\n case \"addFirst\":\n case \"offerFirst\":\n case \"addLast\":\n case \"offerLast\":\n case \"offer\":\n case \"add\":\n case \"push\":\n return function (element: T): any {\n const size = target.size;\n const all = heard.all;\n const result = (value as Function).call(target, element);\n if (added(target.size, size, heard, all)) {\n emitter.emit(prop === \"addFirst\" || prop === \"offerFirst\" ? \"addFirst\" : \"addLast\", { value: element });\n }\n return result;\n };\n\n case \"removeFirst\":\n case \"pollFirst\":\n case \"poll\":\n case \"dequeue\":\n return function (): T {\n const removed = (value as Function).call(target);\n if (removed !== undefined) {\n emitter.emit(\"removeFirst\", { value: removed });\n }\n return removed;\n };\n\n case \"removeLast\":\n case \"pollLast\":\n case \"pop\":\n return function (): T {\n const removed = (value as Function).call(target);\n if (removed !== undefined) {\n emitter.emit(\"removeLast\", { value: removed });\n }\n return removed;\n };\n\n case \"pollOrUndefined\":\n return function (): T | undefined {\n const size = target.size;\n const removed = (value as Function).call(target);\n if (target.size < size) emitter.emit(\"removeFirst\", { value: removed });\n return removed;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => {\n const size = target.size;\n const all = heard.all;\n (receiver as Deque<T>).addLast(element);\n return added(target.size, size, heard, all);\n });\n };\n\n case \"remove\":\n case \"removeAll\":\n case \"retainAll\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n const removed = removalsInOrder(before, after);\n if (removed) {\n for (const removal of removed) emitter.emit(\"remove\", removal);\n return;\n }\n // A base that changed the order of the rest: a clear and the adds give the same contents\n emitter.emit(\"clear\", {});\n for (const element of after) emitter.emit(\"addLast\", { value: element });\n });\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * This function makes an evented Map middleware.\n */\nexport function eventedMap<K, V>(): Middleware<\n MapLike<K, V>,\n MapLike<K, V> & {\n on<E extends keyof MapEvents<K, V>>(\n event: E,\n listener: (payload: MapEvents<K, V>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: MapLike<K, V>) => {\n const emitter = new Emitter<MapEvents<K, V>>();\n const heard = hear<MapRemoval<K, V>>(next, ({ key, value, reason }) => emitter.emit(\"delete\", { key, value, reason }));\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n // Composite methods (computeIfAbsent, compute, merge, putAll and others) go through this\n // proxy's own set and delete, so each change gives its event (C24). The base calls its own set.\n const composite = compositeMapMethod(receiver as MapLike<K, V>, prop);\n if (composite) {\n return composite;\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"set\":\n return function (key: K, val: V): V | undefined {\n const size = target.size;\n const all = heard.all;\n const oldValue = (value as Function).call(target, key, val);\n // A new key that a layer below refused (reject, drop-newest) gives no event\n if (oldValue !== undefined || added(target.size, size, heard, all)) {\n emitter.emit(\"set\", { key, value: val, oldValue });\n }\n return oldValue;\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n const deletedValue = (value as Function).call(target, key);\n if (deletedValue !== undefined) {\n emitter.emit(\"delete\", { key, value: deletedValue });\n }\n return deletedValue;\n };\n\n // The first or last entry of a navigable map (treeMap)\n case \"pollFirstEntry\":\n case \"pollLastEntry\":\n return function (): Entry<K, V> | undefined {\n const entry: Entry<K, V> | undefined = (value as Function).call(target);\n if (entry !== undefined) emitter.emit(\"delete\", { key: entry.key, value: entry.value });\n return entry;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * Generic evented collection middleware.\n */\nexport function evented<T>(): Middleware<\n Collection<T>,\n Collection<T> & {\n on<E extends keyof CollectionEvents<T>>(\n event: E,\n listener: (payload: CollectionEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: Collection<T>) => {\n const emitter = new Emitter<CollectionEvents<T>>();\n hear<ElementRemoval<T>>(next, ({ value, reason }) => emitter.emit(\"remove\", { value, reason }));\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"add\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n emitter.emit(\"add\", { value: element });\n }\n return result;\n };\n\n case \"remove\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n emitter.emit(\"remove\", { value: element });\n }\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n let changed = false;\n for (const element of Array.from(elements)) {\n if ((receiver as Collection<T>).add(element)) changed = true;\n }\n return changed;\n };\n\n case \"removeAll\":\n case \"retainAll\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n for (const removed of removedValues(before, after)) emitter.emit(\"remove\", { value: removed });\n });\n\n // The first or last element of a sorted set (treeSet)\n case \"pollFirst\":\n case \"pollLast\":\n return function (): T | undefined {\n const size = target.size;\n const removed = (value as Function).call(target);\n if (target.size < size) emitter.emit(\"remove\", { value: removed });\n return removed;\n };\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n","/**\n * Synchronized behavior: this module gives thread-safe access with mutex locking.\n *\n * This module wraps collections to serialize all operations using a mutex, making sure that\n * thread-safe access in concurrent environments. Mirrors Java's\n * Collections.synchronizedList() and related methods.\n *\n * Note: JavaScript is single-threaded, but async operations can interleave.\n * This middleware makes sure that atomic operations across async boundaries.\n *\n * @example\n * const list = compose(\n * synchronized()\n * )(arrayList<number>())\n *\n * // All operations are now serialized\n * await Promise.all([\n * list.add(1),\n * list.add(2),\n * list.add(3)\n * ])\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\n\n/**\n * Simple mutex implementation for JavaScript async operations.\n *\n * This middleware makes sure that only one operation starts at a time, even if\n * multiple async operations are started concurrently.\n */\n/** True for an `async` function or method. */\nfunction isAsyncFunction(value: unknown): boolean {\n return typeof value === \"function\" && (value as { [Symbol.toStringTag]?: string })[Symbol.toStringTag] === \"AsyncFunction\";\n}\n\nclass Mutex {\n private queue: Promise<void> = Promise.resolve();\n\n /**\n * This method acquires the lock and starts the function.\n * Other operations wait until this completes.\n */\n async lock<T>(fn: () => T | Promise<T>): Promise<T> {\n const run = this.queue.then(() => fn());\n this.queue = run.then(\n () => undefined,\n () => undefined\n );\n return run;\n }\n\n /**\n * Synchronous version that starts immediately.\n * Still queues to prevent interleaving with async operations.\n */\n\n}\n\n/**\n * This function makes a synchronized middleware that locks all method calls.\n *\n * Every method call on the collection is wrapped with a mutex,\n * making sure that atomic execution even in concurrent async scenarios.\n *\n * @example\n * const syncList = compose(\n * synchronized()\n * )(arrayList<number>())\n *\n * // These additions are guaranteed to execute in order\n * await Promise.all([\n * syncList.add(1),\n * syncList.add(2),\n * syncList.add(3)\n * ])\n */\nexport function synchronized<C extends object>(): Middleware<C> {\n return (next: C): C => {\n const mutex = new Mutex();\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Don't wrap non-functions\n if (typeof value !== \"function\") {\n return value;\n }\n\n // An async method runs inside the lock: it starts after the earlier async calls end.\n // (Before, every method ran first and took the lock after, so nothing was excluded:\n // BUGS-2026-07 L11.) A plain method runs at once: JavaScript does not interrupt it.\n // When a plain method returns a promise anyway, the lock waits for that promise.\n if (isAsyncFunction(value)) {\n return function (this: unknown, ...args: unknown[]) {\n return mutex.lock(() => (value as Function).apply(target, args));\n };\n }\n return function (this: unknown, ...args: unknown[]) {\n const result = (value as Function).apply(target, args);\n if (result instanceof Promise) {\n return mutex.lock(() => result);\n }\n return result;\n };\n },\n }) as C;\n };\n}\n\n/**\n * Alias for Java compatibility: synchronizedList\n */\nexport const synchronizedList : typeof synchronized = synchronized;\n\n/**\n * Alias for Java compatibility: synchronizedMap\n */\nexport const synchronizedMap : typeof synchronized = synchronized;\n\n/**\n * Alias for Java compatibility: synchronizedCollection\n */\nexport const synchronizedCollection : typeof synchronized = synchronized;\n\n/**\n * Alias for Java compatibility: synchronizedSet\n */\nexport const synchronizedSet : typeof synchronized = synchronized;\n\n/**\n * Advanced synchronized middleware with reentrant locking.\n *\n * With this function, the same \"thread\" (async context) can acquire the lock multiple times.\n * Useful for methods that call other synchronized methods internally.\n *\n * Note: JavaScript has no true thread IDs. This function uses async context\n * tracking if available. If not, the behavior is non-reentrant.\n */\nexport function reentrantSynchronized<C extends object>(): Middleware<C> {\n return (next: C): C => {\n const mutex = new Mutex();\n let lockHolder: symbol | null = null;\n let lockCount = 0;\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n return async function (this: any, ...args: any[]) {\n // Generate a unique ID for this call context\n const callerId = Symbol(\"caller\");\n\n // If we already hold the lock, execute directly (reentrant)\n if (lockHolder === callerId) {\n lockCount++;\n try {\n const result = (value as Function).apply(target, args);\n return result instanceof Promise ? await result : result;\n } finally {\n lockCount--;\n }\n }\n\n // Otherwise, acquire the lock\n return mutex.lock(async () => {\n lockHolder = callerId;\n lockCount = 1;\n try {\n const result = (value as Function).apply(target, args);\n return result instanceof Promise ? await result : result;\n } finally {\n lockCount--;\n if (lockCount === 0) {\n lockHolder = null;\n }\n }\n });\n };\n },\n }) as C;\n };\n}\n\n/**\n * Read-write lock implementation for collections.\n *\n * With this function, multiple concurrent readers can read, but a writer is exclusive.\n * More efficient than full synchronization for read-heavy workloads.\n *\n * @example\n * const list = compose(\n * readWriteLock()\n * )(arrayList<number>())\n *\n * // Multiple reads can happen concurrently\n * await Promise.all([\n * list.get(0),\n * list.get(1),\n * list.get(2)\n * ])\n */\nexport function readWriteLock<C extends object>(): Middleware<C> {\n return (next: C): C => {\n let readers = 0;\n let writer = false;\n let waitingReaders: (() => void)[] = [];\n let waitingWriters: (() => void)[] = [];\n\n // Hand-off rule: the releaser counts the waiters it wakes (readers += n, or writer = true),\n // so a woken waiter does not count itself again. (Before, releaseWrite set readers = n and\n // each woken reader added 1, so the count never came back to 0 and writers waited forever:\n // BUGS-2026-07 L11.)\n const acquireRead = async (): Promise<void> => {\n if (writer || waitingWriters.length > 0) {\n await new Promise<void>((resolve) => waitingReaders.push(resolve));\n return;\n }\n readers++;\n };\n\n const releaseRead = (): void => {\n readers--;\n if (readers === 0 && waitingWriters.length > 0) {\n writer = true;\n const next = waitingWriters.shift()!;\n next();\n }\n };\n\n const acquireWrite = async (): Promise<void> => {\n if (writer || readers > 0) {\n await new Promise<void>((resolve) => waitingWriters.push(resolve));\n return;\n }\n writer = true;\n };\n\n const releaseWrite = (): void => {\n writer = false;\n if (waitingWriters.length > 0) {\n writer = true;\n const next = waitingWriters.shift()!;\n next();\n } else if (waitingReaders.length > 0) {\n const allReaders = waitingReaders.splice(0);\n readers += allReaders.length;\n allReaders.forEach((resolve) => resolve());\n }\n };\n\n // Methods that only read (don't mutate)\n const READ_METHODS = new Set([\n \"get\",\n \"has\",\n \"contains\",\n \"containsAll\",\n \"containsValue\",\n \"indexOf\",\n \"lastIndexOf\",\n \"peek\",\n \"peekFirst\",\n \"peekLast\",\n \"first\",\n \"last\",\n \"isEmpty\",\n \"size\",\n \"toArray\",\n \"keys\",\n \"values\",\n \"entries\",\n \"forEach\",\n \"getOrDefault\",\n \"getOrUndefined\",\n \"descendingIterator\",\n ]);\n\n // The reads that give an iterator. The lock copies the elements before it releases the read (C32).\n const ITERATOR_READS = new Set([\"keys\", \"values\", \"entries\", \"descendingIterator\"]);\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n // A method with a symbol key, for example Symbol.iterator, stays synchronous, so `for of` works (C32).\n // The loop reads at once with no lock, as a plain method of synchronized().\n if (typeof prop === \"symbol\") {\n return function (this: unknown, ...args: unknown[]) {\n return (value as Function).apply(target, args);\n };\n }\n\n const isReadMethod = READ_METHODS.has(prop);\n const isIteratorRead = ITERATOR_READS.has(prop);\n\n return async function (this: any, ...args: any[]) {\n if (isReadMethod) {\n // Acquire read lock\n await acquireRead();\n try {\n const raw = (value as Function).apply(target, args);\n const result = raw instanceof Promise ? await raw : raw;\n // Before C32, the iteration started after the release of the read, so a write could change the elements.\n return isIteratorRead && result != null && typeof result[Symbol.iterator] === \"function\"\n ? Array.from(result as Iterable<unknown>)[Symbol.iterator]()\n : result;\n } finally {\n releaseRead();\n }\n } else {\n // Acquire write lock\n await acquireWrite();\n try {\n const result = (value as Function).apply(target, args);\n return result instanceof Promise ? await result : result;\n } finally {\n releaseWrite();\n }\n }\n };\n },\n }) as C;\n };\n}\n","/**\n * LRU (Least Recently Used) eviction behavior.\n *\n * This module tracks access times and automatically evicts the least recently used\n * elements when capacity is reached. Perfect for caching.\n *\n * @example\n * const cache = compose(\n * lruMap<string, Data>({ capacity: 100 })\n * )(hashMap<string, Data>())\n *\n * cache.set('key1', data1) // Accessed\n * cache.get('key1') // Accessed again (moves to front)\n * // When full, least recently accessed keys are evicted\n */\n\nimport { checkCapacity } from \"../core/capacity.js\";\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { compositeMapMethod } from \"./composite.js\";\nimport { removals, removalSource, type MapRemoval } from \"../core/removals.js\";\n\n/**\n * Options for LRU behavior.\n */\nexport interface LRUOptions {\n /**\n * The maximum number of entries, a positive whole number. When the map is full, a new key\n * evicts the least recently used entry.\n */\n capacity: number;\n\n /**\n * Optional callback invoked when an item is evicted.\n */\n onEvict?: (info: { key: any; value: any; timestamp: number }) => void;\n}\n\n/**\n * Metadata for tracking LRU access.\n */\ninterface LRUNode<K, V> {\n key: K;\n value: V;\n lastAccessed: number;\n prev: LRUNode<K, V> | null;\n next: LRUNode<K, V> | null;\n}\n\n/**\n * This function makes an LRU Map middleware.\n *\n * This function maintains a doubly-linked list to track access order.\n * Most recently accessed items are at the head.\n * When capacity is exceeded, items at the tail are evicted.\n *\n * @throws RangeError when `options.capacity` is not a positive whole number.\n */\nexport function lruMap<K, V>(\n options: LRUOptions\n): Middleware<MapLike<K, V>, MapLike<K, V> & { readonly isFull: boolean }> {\n const { onEvict } = options;\n const capacity = checkCapacity(options.capacity, \"lruMap\");\n\n return (next: MapLike<K, V>): MapLike<K, V> & { readonly isFull: boolean } => {\n // Doubly-linked list for LRU tracking\n let head: LRUNode<K, V> | null = null;\n let tail: LRUNode<K, V> | null = null;\n const nodeMap = new Map<K, LRUNode<K, V>>();\n\n const moveToHead = (node: LRUNode<K, V>): void => {\n // Remove from current position\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n tail = node.prev;\n }\n\n // Add to head\n node.prev = null;\n node.next = head;\n if (head) {\n head.prev = node;\n }\n head = node;\n\n if (!tail) {\n tail = node;\n }\n\n node.lastAccessed = Date.now();\n };\n\n const addNode = (key: K, value: V): void => {\n const node: LRUNode<K, V> = {\n key,\n value,\n lastAccessed: Date.now(),\n prev: null,\n next: head,\n };\n\n if (head) {\n head.prev = node;\n }\n head = node;\n\n if (!tail) {\n tail = node;\n }\n\n nodeMap.set(key, node);\n };\n\n const removeNode = (node: LRUNode<K, V>): void => {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n tail = node.prev;\n }\n\n nodeMap.delete(node.key);\n };\n\n // A removal below (for example an expiry of ttlMap, in compose(lruMap, ttlMap)) removes the node of its key\n const source = removalSource<MapRemoval<K, V>>(next, ({ key }) => {\n const node = nodeMap.get(key);\n if (node) removeNode(node);\n });\n\n // A layer below with no removal channel can remove an entry without this layer seeing it. Its node is\n // then stale: the list must not keep it (it holds the value, and it would grow without bound) and evicting\n // it is not an eviction. With the channel, no node is stale and these checks find nothing.\n const dropStaleNodes = (): void => {\n for (const node of [...nodeMap.values()]) {\n if (!next.has(node.key)) {\n removeNode(node);\n }\n }\n };\n\n const evictLRU = (): void => {\n while (tail) {\n const candidate = tail;\n removeNode(candidate);\n if (!next.has(candidate.key)) {\n // Already removed below: skip it and evict the next least recently used entry\n continue;\n }\n next.delete(candidate.key);\n\n if (onEvict) {\n onEvict({\n key: candidate.key,\n value: candidate.value,\n timestamp: candidate.lastAccessed,\n });\n }\n source.emit({ key: candidate.key, value: candidate.value, reason: \"evict\" });\n return;\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) {\n return source.channel;\n }\n // Add isFull property\n if (prop === \"isFull\") {\n return target.size >= capacity;\n }\n\n // Composite methods (setIfAbsent, compute, merge, putAll and others) go through this\n // proxy's own primitives, so they keep this behavior's rules (BUGS-2026-07 L13)\n const composite = compositeMapMethod(receiver as MapLike<K, V>, prop);\n if (composite) {\n return composite;\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"get\":\n return function (key: K): V {\n const result: V = (value as Function).call(target, key);\n // Update access time\n const node = nodeMap.get(key);\n if (node) {\n moveToHead(node);\n }\n return result;\n };\n\n case \"has\":\n return function (key: K): boolean {\n const result = (value as Function).call(target, key);\n const node = nodeMap.get(key);\n if (node && result) {\n // Update access time\n moveToHead(node);\n }\n return result;\n };\n\n case \"set\":\n return function (key: K, val: V): V | undefined {\n const hadKey = target.has(key);\n\n if (hadKey) {\n // Update existing\n const oldValue = (value as Function).call(target, key, val);\n const node = nodeMap.get(key);\n if (node) {\n node.value = val;\n moveToHead(node);\n }\n return oldValue;\n } else {\n // Add new. A stale node for this key (its entry was removed below) must not\n // stay in the list: evicting it later would delete the new node's map entry.\n const stale = nodeMap.get(key);\n if (stale) {\n removeNode(stale);\n }\n // Keep the node list bounded. At most `capacity` nodes are live, so at twice the capacity a scan\n // removes at least `capacity` stale nodes: the cost of a set is amortized O(1). A scan at the\n // capacity read each node at each set into a full map (C10). evictLRU skips the other stale nodes.\n if (nodeMap.size >= 2 * capacity) {\n dropStaleNodes();\n }\n if (target.size >= capacity) {\n evictLRU();\n }\n const result = (value as Function).call(target, key, val);\n addNode(key, val);\n return result;\n }\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n const result = (value as Function).call(target, key);\n const node = nodeMap.get(key);\n if (node) {\n removeNode(node);\n }\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n head = null;\n tail = null;\n nodeMap.clear();\n };\n }\n }\n\n return value;\n },\n }) as MapLike<K, V> & { readonly isFull: boolean };\n };\n}\n\n/**\n * This class makes an LRU cache with a simpler API.\n * This is a standalone LRU cache implementation.\n *\n * @example\n * const cache = lruCache<string, Data>(100)\n * cache.set('key', value)\n * cache.get('key') // Moves to front\n */\nexport class LRUCache<K, V> {\n private readonly capacity: number;\n private readonly onEvict: ((key: K, value: V) => void) | undefined;\n private map: Map<K, { value: V; node: LRUNode<K, V> }> = new Map();\n private head: LRUNode<K, V> | null = null;\n private tail: LRUNode<K, V> | null = null;\n\n /**\n * @param capacity - The maximum number of entries, a positive whole number.\n * @param onEvict - The function that this cache starts for each entry that it evicts.\n * @throws RangeError when `capacity` is not a positive whole number.\n */\n constructor(capacity: number, onEvict?: ((key: K, value: V) => void) | undefined) {\n this.capacity = checkCapacity(capacity, \"LRUCache\");\n this.onEvict = onEvict;\n }\n\n get size(): number {\n return this.map.size;\n }\n\n get isFull(): boolean {\n return this.map.size >= this.capacity;\n }\n\n get(key: K): V | undefined {\n const entry = this.map.get(key);\n if (!entry) return undefined;\n\n this.moveToHead(entry.node);\n return entry.value;\n }\n\n set(key: K, value: V): void {\n const entry = this.map.get(key);\n\n if (entry) {\n // Update existing\n entry.value = value;\n entry.node.value = value;\n this.moveToHead(entry.node);\n } else {\n // Add new\n if (this.map.size >= this.capacity) {\n this.evictLRU();\n }\n\n const node: LRUNode<K, V> = {\n key,\n value,\n lastAccessed: Date.now(),\n prev: null,\n next: this.head,\n };\n\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n\n if (!this.tail) {\n this.tail = node;\n }\n\n this.map.set(key, { value, node });\n }\n }\n\n has(key: K): boolean {\n return this.map.has(key);\n }\n\n delete(key: K): boolean {\n const entry = this.map.get(key);\n if (!entry) return false;\n\n this.removeNode(entry.node);\n this.map.delete(key);\n return true;\n }\n\n /**\n * This method deletes each entry for which `matches` gives true, and it gives the number of\n * deleted entries. It is not a use: the order of the other entries does not change, and it\n * does not start `onEvict`. It starts `matches` once for each entry, the most recent first. If\n * `matches` throws, the entries that it matched before stay deleted.\n *\n * @param matches - The test of an entry.\n * @returns The number of deleted entries.\n */\n deleteWhere(matches: (value: V, key: K) => boolean): number {\n const nodes: LRUNode<K, V>[] = [];\n for (let node = this.head; node; node = node.next) nodes.push(node);\n let deleted = 0;\n for (const node of nodes) {\n // The function `matches` can change the cache. Skip each node that is not in it now.\n if (this.map.get(node.key)?.node !== node) continue;\n if (!matches(node.value, node.key)) continue;\n // The function `matches` can delete this node itself, so check again.\n if (this.map.get(node.key)?.node !== node) continue;\n this.removeNode(node);\n this.map.delete(node.key);\n deleted++;\n }\n return deleted;\n }\n\n clear(): void {\n this.map.clear();\n this.head = null;\n this.tail = null;\n }\n\n private moveToHead(node: LRUNode<K, V>): void {\n if (node === this.head) return;\n\n // Remove from current position\n if (node.prev) {\n node.prev.next = node.next;\n }\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n\n // Add to head\n node.prev = null;\n node.next = this.head;\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n\n node.lastAccessed = Date.now();\n }\n\n private removeNode(node: LRUNode<K, V>): void {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this.head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n }\n\n private evictLRU(): void {\n if (!this.tail) return;\n\n const evicted = this.tail;\n this.removeNode(evicted);\n this.map.delete(evicted.key);\n\n if (this.onEvict) {\n this.onEvict(evicted.key, evicted.value);\n }\n }\n\n /**\n * This method gives keys in LRU order (most recent first).\n */\n *keys(): IterableIterator<K> {\n let node = this.head;\n while (node) {\n yield node.key;\n node = node.next;\n }\n }\n\n /**\n * This method gives entries in LRU order (most recent first).\n */\n *entries(): IterableIterator<[K, V]> {\n let node = this.head;\n while (node) {\n yield [node.key, node.value];\n node = node.next;\n }\n }\n}\n\n/**\n * This function makes an LRU cache.\n *\n * @throws RangeError when `capacity` is not a positive whole number.\n */\nexport function lruCache<K, V>(\n capacity: number,\n onEvict?: (key: K, value: V) => void\n): LRUCache<K, V> {\n return new LRUCache(capacity, onEvict);\n}\n","/**\n * TTL (Time-To-Live) expiration behavior.\n *\n * The behavior removes each element when its time to live ends.\n * Perfect for temporary caches and time-limited data.\n *\n * @example\n * const cache = compose(\n * ttlMap<string, Data>({ ttl: 60000 }) // 60 seconds\n * )(hashMap<string, Data>())\n *\n * cache.set('key', data)\n * // After 60 seconds, 'key' is automatically removed\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { Entry, MapLike } from \"../interfaces/map.js\";\nimport { compositeMapMethod } from \"./composite.js\";\nimport { removals, removalSource, type ElementRemoval, type MapRemoval } from \"../core/removals.js\";\nimport type { Collection } from \"../interfaces/collection.js\";\n\n/**\n * This function starts the background expiration checker, and it does not keep a Node.js process alive.\n * (In a browser, setInterval gives a number and there is nothing to unref.)\n */\nfunction startExpirationTimer(check: () => void, interval: number): ReturnType<typeof setInterval> {\n const timer = setInterval(check, interval);\n (timer as unknown as { unref?: () => void }).unref?.();\n return timer;\n}\n\n/**\n * Options for TTL behavior.\n */\nexport interface TTLOptions {\n /**\n * Time-to-live in milliseconds.\n * Elements expire after this duration.\n */\n ttl: number;\n\n /**\n * Interval for checking expired elements (in milliseconds).\n * @default 1000 (check every second)\n */\n checkInterval?: number;\n\n /**\n * Optional callback invoked when an element expires.\n */\n onExpire?: (info: { key: any; value: any; createdAt: number; expiredAt: number }) => void;\n}\n\n/**\n * Metadata for TTL tracking.\n */\ninterface TTLEntry<V> {\n value: V;\n expiresAt: number;\n createdAt: number;\n}\n\n/**\n * This function makes a TTL Map middleware.\n *\n * An entry is live while the time is less than the time of its last `set` plus `ttl`.\n * Each access to the map first removes the expired entries, so each read shows only live entries.\n * The layer gives each expired entry to `onExpire` one time, in the order of expiry.\n * A background interval also removes expired entries, so `onExpire` occurs with no access.\n *\n * The layer keeps the times in the order of expiry, so the removal before an access is amortized O(1).\n * This order needs a clock that does not go back. If `Date.now()` goes back, an entry can stay until the entries before it expire.\n */\nexport function ttlMap<K, V>(\n options: TTLOptions\n): Middleware<MapLike<K, V>, MapLike<K, V> & { readonly dispose: () => void }> {\n const { ttl, checkInterval = 1000, onExpire } = options;\n\n return (\n next: MapLike<K, V>\n ): MapLike<K, V> & { readonly dispose: () => void } => {\n // The times of the live keys, in the order of expiry: a set deletes its key before it adds it again\n const metadata = new Map<K, TTLEntry<V>>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n // A removal below (for example an eviction of lruMap) ends the time of its key, so it never expires\n const source = removalSource<MapRemoval<K, V>>(next, ({ key }) => void metadata.delete(key));\n\n // This function removes the expired entries from the front of the order, and stops at the first live entry\n const sweep = (): void => {\n const now = Date.now();\n for (const [key, entry] of metadata) {\n if (now < entry.expiresAt) return;\n metadata.delete(key);\n next.delete(key);\n onExpire?.({ key, value: entry.value, createdAt: entry.createdAt, expiredAt: now });\n source.emit({ key, value: entry.value, reason: \"expire\" });\n }\n };\n\n intervalId = startExpirationTimer(sweep, checkInterval);\n\n const dispose = (): void => {\n if (intervalId) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"dispose\") {\n return dispose;\n }\n if (prop === removals) {\n return source.channel;\n }\n\n // Composite methods (setIfAbsent, compute, merge, putAll and others) go through this\n // proxy's own primitives, so they keep the expiry rules (BUGS-2026-07 L13)\n const composite = compositeMapMethod(receiver as MapLike<K, V>, prop);\n if (composite) {\n return composite;\n }\n\n // A getter (size, isEmpty) reads only live entries\n sweep();\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== \"function\") {\n return value;\n }\n\n switch (prop) {\n case \"set\":\n return function (key: K, val: V): V | undefined {\n sweep();\n const result = (value as Function).call(target, key, val);\n const now = Date.now();\n metadata.delete(key);\n metadata.set(key, { value: val, expiresAt: now + ttl, createdAt: now });\n return result;\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n sweep();\n metadata.delete(key);\n return (value as Function).call(target, key);\n };\n\n case \"clear\":\n return function (): void {\n metadata.clear();\n (value as Function).call(target);\n };\n\n // The iteration gives the entries that are live when it starts. A removal while it runs (by a read in\n // the loop, or by the interval between the steps of an async loop) does not change it, so the base\n // iterator never sees a change and never throws.\n case Symbol.iterator:\n case \"entries\":\n return function (): IterableIterator<Entry<K, V>> {\n sweep();\n return Array.from(target as Iterable<Entry<K, V>>).values();\n };\n\n case \"keys\":\n return function (): IterableIterator<K> {\n sweep();\n return Array.from(target as Iterable<Entry<K, V>>, (e) => e.key).values();\n };\n\n case \"values\":\n return function (): IterableIterator<V> {\n sweep();\n return Array.from(target as Iterable<Entry<K, V>>, (e) => e.value).values();\n };\n\n case \"forEach\":\n return function (callback: (value: V, key: K, map: MapLike<K, V>) => void): void {\n sweep();\n for (const e of Array.from(target as Iterable<Entry<K, V>>)) callback(e.value, e.key, receiver as MapLike<K, V>);\n };\n\n default:\n // Each other method (get, has, getOrUndefined, the iteration) reads only live entries,\n // also when a caller keeps the method and calls it later\n return function (this: unknown, ...args: unknown[]): unknown {\n sweep();\n return (value as Function).apply(target, args);\n };\n }\n },\n }) as MapLike<K, V> & { readonly dispose: () => void };\n };\n}\n\n/**\n * This function makes a TTL Collection middleware.\n *\n * Note: This is less precise than TTL map because collections don't have keys.\n * Elements are tracked by reference, which can fail for primitive types.\n */\nexport function ttlCollection<T>(\n options: Omit<TTLOptions, \"onExpire\"> & {\n onExpire?: (info: { element: T; createdAt: number; expiredAt: number }) => void;\n }\n): Middleware<Collection<T>, Collection<T> & { readonly dispose: () => void }> {\n const { ttl, checkInterval = 1000, onExpire } = options;\n\n return (\n next: Collection<T>\n ): Collection<T> & { readonly dispose: () => void } => {\n const metadata = new Map<T, { expiresAt: number; createdAt: number }>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const source = removalSource<ElementRemoval<T>>(next, ({ value }) => void metadata.delete(value));\n\n const checkExpired = (): void => {\n const now = Date.now();\n const expired: T[] = [];\n\n for (const [element, entry] of metadata) {\n if (now >= entry.expiresAt) {\n expired.push(element);\n }\n }\n\n for (const element of expired) {\n const entry = metadata.get(element);\n if (entry) {\n next.remove(element);\n metadata.delete(element);\n\n if (onExpire) {\n onExpire({\n element,\n createdAt: entry.createdAt,\n expiredAt: now,\n });\n }\n source.emit({ value: element, reason: \"expire\" });\n }\n }\n };\n\n intervalId = startExpirationTimer(checkExpired, checkInterval);\n\n const dispose = (): void => {\n if (intervalId) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"dispose\") {\n return dispose;\n }\n if (prop === removals) {\n return source.channel;\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"add\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n const now = Date.now();\n metadata.set(element, {\n expiresAt: now + ttl,\n createdAt: now,\n });\n }\n return result;\n };\n\n case \"remove\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n metadata.delete(element);\n }\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n metadata.clear();\n };\n }\n }\n\n return value;\n },\n }) as Collection<T> & { readonly dispose: () => void };\n };\n}\n\n/**\n * Standalone TTL cache with Map-like API.\n *\n * @example\n * const cache = new TTLCache<string, number>(60000) // 60 second TTL\n * cache.set('key', 42)\n * setTimeout(() => {\n * cache.get('key') // undefined (expired)\n * }, 61000)\n */\nexport class TTLCache<K, V> {\n private readonly ttl: number;\n private readonly checkInterval: number;\n private readonly onExpire: ((key: K, value: V) => void) | undefined;\n private map = new Map<K, TTLEntry<V>>();\n private intervalId: ReturnType<typeof setInterval> | null = null;\n\n constructor(ttl: number, checkInterval: number = 1000, onExpire?: ((key: K, value: V) => void) | undefined) {\n this.ttl = ttl;\n this.checkInterval = checkInterval;\n this.onExpire = onExpire;\n this.startExpirationCheck();\n }\n\n get size(): number {\n this.cleanup();\n return this.map.size;\n }\n\n get(key: K): V | undefined {\n const entry = this.map.get(key);\n if (!entry) return undefined;\n\n if (Date.now() >= entry.expiresAt) {\n this.map.delete(key);\n if (this.onExpire) {\n this.onExpire(key, entry.value);\n }\n return undefined;\n }\n\n return entry.value;\n }\n\n set(key: K, value: V, customTTL?: number): void {\n const now = Date.now();\n const ttlToUse = customTTL !== undefined ? customTTL : this.ttl;\n\n this.map.set(key, {\n value,\n expiresAt: now + ttlToUse,\n createdAt: now,\n });\n }\n\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n delete(key: K): boolean {\n return this.map.delete(key);\n }\n\n clear(): void {\n this.map.clear();\n }\n\n /**\n * This method removes the expired entries at once.\n */\n cleanup(): void {\n const now = Date.now();\n const expired: K[] = [];\n\n for (const [key, entry] of this.map) {\n if (now >= entry.expiresAt) {\n expired.push(key);\n }\n }\n\n for (const key of expired) {\n const entry = this.map.get(key);\n if (entry) {\n this.map.delete(key);\n if (this.onExpire) {\n this.onExpire(key, entry.value);\n }\n }\n }\n }\n\n /**\n * This method gives the remaining TTL of a key, in milliseconds.\n * This method gives undefined if key doesn't exist or is expired.\n */\n getTTL(key: K): number | undefined {\n const entry = this.map.get(key);\n if (!entry) return undefined;\n\n const remaining = entry.expiresAt - Date.now();\n return remaining > 0 ? remaining : undefined;\n }\n\n /**\n * This method updates the TTL of a key that is in the map.\n */\n touch(key: K, customTTL?: number): boolean {\n const entry = this.map.get(key);\n if (!entry) return false;\n\n if (Date.now() >= entry.expiresAt) {\n this.map.delete(key);\n return false;\n }\n\n const ttlToUse = customTTL !== undefined ? customTTL : this.ttl;\n entry.expiresAt = Date.now() + ttlToUse;\n return true;\n }\n\n private startExpirationCheck(): void {\n this.intervalId = startExpirationTimer(() => this.cleanup(), this.checkInterval);\n }\n\n /**\n * This method stops the background expiration checker and cleans up.\n */\n dispose(): void {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n }\n\n *keys(): IterableIterator<K> {\n this.cleanup();\n yield* this.map.keys();\n }\n\n *values(): IterableIterator<V> {\n this.cleanup();\n for (const entry of this.map.values()) {\n yield entry.value;\n }\n }\n\n *entries(): IterableIterator<[K, V]> {\n this.cleanup();\n for (const [key, entry] of this.map) {\n yield [key, entry.value];\n }\n }\n}\n\n/**\n * Factory function to make a TTL cache.\n */\nexport function ttlCache<K, V>(\n ttl: number,\n options?: {\n checkInterval?: number;\n onExpire?: (key: K, value: V) => void;\n }\n): TTLCache<K, V> {\n return new TTLCache(\n ttl,\n options?.checkInterval,\n options?.onExpire\n );\n}\n","/**\n * AsyncQueue - An async iterable queue with backpressure support.\n *\n * The queue is for producer-consumer patterns where producers can wait when\n * the queue is full and consumers can wait when the queue is empty.\n * This module implements AsyncIterable for use with for-await-of loops.\n *\n * @example\n * const queue = asyncQueue<number>({ capacity: 10 })\n *\n * // Producer\n * await queue.put(42) // Waits if queue is full\n *\n * // Consumer\n * const value = await queue.take() // Waits if queue is empty\n *\n * // Async iteration\n * for await (const value of queue) {\n * console.log(value)\n * }\n */\n\nimport type { AsyncQueue as IAsyncQueue } from \"../interfaces/queue.js\";\n\n/** The text of the error of a put, a new one or a waiting one, on a closed queue. */\nconst CLOSED = \"Queue is closed\";\n\n/** The text of the error of a take, a peek or a wait on a queue that is closed and empty. */\nconst CLOSED_AND_EMPTY = \"Queue is closed and empty\";\n\n/**\n * Options for making an AsyncQueue.\n */\nexport interface AsyncQueueOptions {\n /**\n * The maximum number of elements: a whole number of 0 or more, or `Infinity` for no bound.\n * Any other value gives a `RangeError`.\n * @default Infinity\n */\n capacity?: number;\n\n /**\n * Timeout for put/take operations in milliseconds.\n * @default undefined (no timeout)\n */\n timeout?: number;\n}\n\n/**\n * Resolver for waiting operations.\n */\ninterface Resolver<T> {\n resolve: (value: T) => void;\n reject: (reason: any) => void;\n timeoutId?: ReturnType<typeof setTimeout>;\n}\n\n/** A waiting put: it keeps its element until the queue takes it. */\ninterface Putter<T> extends Resolver<void> {\n element: T;\n}\n\n/**\n * AsyncQueue<T> - Thread-safe async queue with backpressure.\n *\n * Features:\n * - Blocking put() when full (backpressure)\n * - Blocking take() when empty\n * - AsyncIterable support\n * - Graceful closing\n * - Timeouts\n *\n * Perfect for:\n * - Producer-consumer patterns\n * - Rate limiting\n * - Task queues\n * - Stream processing\n */\nexport class AsyncQueue<T> implements IAsyncQueue<T> {\n private buffer: T[] = [];\n private putters: Putter<T>[] = [];\n private takers: Resolver<T>[] = [];\n /** The calls of `peek` that wait: they see the next element, but they do not take it. */\n private peekers: Resolver<T>[] = [];\n private _isClosed = false;\n private readonly capacity: number;\n private readonly defaultTimeout?: number;\n\n constructor(options: AsyncQueueOptions = {}) {\n const capacity = options.capacity ?? Infinity;\n // A capacity of -1, 1.5 or NaN gave a wrong remainingCapacity, or each put waited with no end.\n if (capacity !== Infinity && !(Number.isInteger(capacity) && capacity >= 0)) {\n throw new RangeError(`The capacity must be a whole number of 0 or more, or Infinity: ${String(capacity)}`);\n }\n this.capacity = capacity;\n if (options.timeout !== undefined) {\n this.defaultTimeout = options.timeout;\n }\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this.buffer.length;\n }\n\n get isEmpty(): boolean {\n return this.buffer.length === 0;\n }\n\n get isFull(): boolean {\n return this.buffer.length >= this.capacity;\n }\n\n get isClosed(): boolean {\n return this._isClosed;\n }\n\n get remainingCapacity(): number {\n return this.capacity === Infinity ? Infinity : this.capacity - this.buffer.length;\n }\n\n // ========================================================================\n // Blocking operations\n // ========================================================================\n\n /**\n * This method adds an element to the queue.\n * If the queue is full, waits until space is available. With a capacity of 0, it waits until\n * a taker takes the element (a rendezvous).\n *\n * @throws Error if queue is closed\n * @throws Error if timeout expires\n */\n async put(element: T, timeout?: number): Promise<void> {\n if (this._isClosed) {\n throw new Error(CLOSED);\n }\n if (this.tryPutNow(element)) {\n return;\n }\n\n // A waiting peek sees the element of a waiting put (a capacity of 0)\n this.wakePeekers(element);\n\n // Queue is full: wait with the element. (Before, a waiting putter kept only its resolve\n // function, so its element was dropped when space came: BUGS-2026-07 C11.)\n return new Promise<void>((resolve, reject) => {\n const putter: Putter<T> = { element, resolve, reject };\n const timeoutMs = timeout ?? this.defaultTimeout;\n if (timeoutMs !== undefined) {\n putter.timeoutId = setTimeout(() => {\n const index = this.putters.indexOf(putter);\n if (index !== -1) {\n this.putters.splice(index, 1);\n }\n reject(new Error(`Put timeout after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n this.putters.push(putter);\n });\n }\n\n /**\n * This method removes an element from the queue and gives it.\n * If the queue is empty, waits until an element is available.\n *\n * @throws Error if queue is closed and empty\n * @throws Error if timeout expires\n */\n async take(timeout?: number): Promise<T> {\n const next = this.takeNow();\n if (next.found) {\n return next.element;\n }\n\n // If closed and empty, throw\n if (this._isClosed) {\n throw new Error(CLOSED_AND_EMPTY);\n }\n\n // Wait for an element\n return new Promise<T>((resolve, reject) => {\n const taker: Resolver<T> = { resolve, reject };\n const timeoutMs = timeout ?? this.defaultTimeout;\n if (timeoutMs !== undefined) {\n taker.timeoutId = setTimeout(() => {\n const index = this.takers.indexOf(taker);\n if (index !== -1) {\n this.takers.splice(index, 1);\n }\n reject(new Error(`Take timeout after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n this.takers.push(taker);\n });\n }\n\n /**\n * This method waits for the next element, as `take` does, but it gives the element to\n * `onElement` and the closure of the queue to `onClosed`. These calls are synchronous: they\n * occur in the call that adds the element or closes the queue. The method has no timeout.\n *\n * The function that it gives withdraws the wait. A withdrawn wait gets no element, so no\n * element goes to a taker that left. `select` races its cases with this method.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no element yet.\n */\n waitTake(onElement: (element: T) => void, onClosed: (error: Error) => void): () => boolean {\n const next = this.takeNow();\n if (next.found) {\n onElement(next.element);\n return () => false;\n }\n if (this._isClosed) {\n onClosed(new Error(CLOSED_AND_EMPTY));\n return () => false;\n }\n const taker: Resolver<T> = { resolve: onElement, reject: onClosed };\n this.takers.push(taker);\n return () => {\n const index = this.takers.indexOf(taker);\n if (index === -1) return false;\n this.takers.splice(index, 1);\n return true;\n };\n }\n\n // ========================================================================\n // Non-blocking operations\n // ========================================================================\n\n /**\n * This method tries to add an element without waiting.\n * This method gives false if queue is full (with a capacity of 0: if no taker waits).\n */\n tryPut(element: T): boolean {\n if (this._isClosed) {\n return false;\n }\n return this.tryPutNow(element);\n }\n\n /**\n * This method tries to remove an element without waiting.\n * This method gives undefined if queue is empty.\n */\n tryTake(): T | undefined {\n const next = this.takeNow();\n return next.found ? next.element : undefined;\n }\n\n /** This method gives the element to a waiting taker, or puts it in the buffer when there is space. */\n private tryPutNow(element: T): boolean {\n // A waiting taker gets the element directly (the buffer is empty when a taker waits)\n const taker = this.takers.shift();\n if (taker) {\n this.wakePeekers(element);\n this.clearTimeout(taker);\n taker.resolve(element);\n return true;\n }\n if (this.buffer.length < this.capacity) {\n this.buffer.push(element);\n this.wakePeekers(element);\n return true;\n }\n return false;\n }\n\n /** Each waiting peek gets the element, which stays where it is. */\n private wakePeekers(element: T): void {\n const peekers = this.peekers;\n this.peekers = [];\n for (const peeker of peekers) {\n this.clearTimeout(peeker);\n peeker.resolve(element);\n }\n }\n\n /**\n * This method takes the next element: from the buffer (then a waiting putter moves its element into the\n * buffer), or directly from a waiting putter (a capacity of 0). (Before, the direct path\n * released the putter but did not give its element to the taker, so the taker waited forever:\n * BUGS-2026-07 C11.)\n */\n private takeNow(): { found: true; element: T } | { found: false } {\n if (this.buffer.length > 0) {\n const element = this.buffer.shift()!;\n this.admitPutter();\n return { found: true, element };\n }\n const putter = this.putters.shift();\n if (putter) {\n this.clearTimeout(putter);\n putter.resolve();\n return { found: true, element: putter.element };\n }\n return { found: false };\n }\n\n // ========================================================================\n // Peeking\n // ========================================================================\n\n /**\n * This method gives the next element without removing it.\n * Waits if queue is empty.\n */\n async peek(): Promise<T> {\n if (this.buffer.length > 0) {\n return this.buffer[0]!;\n }\n if (this.putters.length > 0) {\n return this.putters[0]!.element;\n }\n\n if (this._isClosed) {\n throw new Error(CLOSED_AND_EMPTY);\n }\n\n // Wait for the next element without a take. (Before, peek took the element and put it back\n // at the front: a take that waited after it kept waiting, and the order changed: audit pass 2.)\n return new Promise<T>((resolve, reject) => {\n const peeker: Resolver<T> = { resolve, reject };\n const timeoutMs = this.defaultTimeout;\n if (timeoutMs !== undefined) {\n peeker.timeoutId = setTimeout(() => {\n const index = this.peekers.indexOf(peeker);\n if (index !== -1) {\n this.peekers.splice(index, 1);\n }\n reject(new Error(`Peek timeout after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n this.peekers.push(peeker);\n });\n }\n\n /**\n * This method gives the next element without waiting.\n * This method gives undefined if queue is empty.\n */\n tryPeek(): T | undefined {\n return this.buffer.length > 0 ? this.buffer[0] : this.putters[0]?.element;\n }\n\n // ========================================================================\n // Closing and draining\n // ========================================================================\n\n /**\n * This method closes the queue. No more elements can be added.\n * Existing elements can still be consumed.\n */\n close(): void {\n this._isClosed = true;\n\n // Reject all waiting putters\n for (const putter of this.putters) {\n this.clearTimeout(putter);\n putter.reject(new Error(CLOSED));\n }\n this.putters = [];\n\n // Wake up takers if queue is empty\n if (this.buffer.length === 0) {\n for (const taker of this.takers) {\n this.clearTimeout(taker);\n taker.reject(new Error(CLOSED_AND_EMPTY));\n }\n this.takers = [];\n for (const peeker of this.peekers) {\n this.clearTimeout(peeker);\n peeker.reject(new Error(CLOSED_AND_EMPTY));\n }\n this.peekers = [];\n }\n }\n\n /**\n * This method drains all elements into an array.\n * This method gives immediately with current elements.\n */\n drain(): T[] {\n // The buffer, then the elements of the waiting putters, in order. (Before, the waiting\n // putters were released but their elements were dropped.)\n const elements = this.buffer.slice();\n this.buffer = [];\n for (const putter of this.putters.splice(0)) {\n this.clearTimeout(putter);\n putter.resolve();\n elements.push(putter.element);\n }\n return elements;\n }\n\n // ========================================================================\n // Async iteration\n // ========================================================================\n\n /**\n * Async iterator that yields elements as they become available.\n * Stops when queue is closed and empty.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n const next = this.takeNow();\n if (next.found) {\n yield next.element;\n } else if (this._isClosed) {\n break;\n } else {\n let element: T;\n try {\n element = await this.take();\n } catch (error) {\n // The queue was closed while the iterator waited\n if (this._isClosed) break;\n throw error;\n }\n yield element;\n }\n }\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n /** When the buffer has space, the first waiting putter moves its element into it. */\n private admitPutter(): void {\n if (this.putters.length > 0 && this.buffer.length < this.capacity) {\n const putter = this.putters.shift()!;\n this.clearTimeout(putter);\n this.buffer.push(putter.element);\n putter.resolve();\n }\n }\n\n private clearTimeout(resolver: Resolver<any>): void {\n if (resolver.timeoutId) {\n clearTimeout(resolver.timeoutId);\n }\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n /**\n * This method gives statistics about the queue.\n */\n getStats() : {\n size: number;\n capacity: number;\n isEmpty: boolean;\n isFull: boolean;\n isClosed: boolean;\n waitingPutters: number;\n waitingTakers: number;\n remainingCapacity: number;\n } {\n return {\n size: this.size,\n capacity: this.capacity,\n isEmpty: this.isEmpty,\n isFull: this.isFull,\n isClosed: this._isClosed,\n waitingPutters: this.putters.length,\n waitingTakers: this.takers.length,\n remainingCapacity: this.remainingCapacity,\n };\n }\n\n toString(): string {\n return `AsyncQueue[size=${this.size}, capacity=${this.capacity}, closed=${this._isClosed}]`;\n }\n}\n\n/**\n * Factory function to make an AsyncQueue.\n *\n * @throws RangeError if the capacity is not a whole number of 0 or more, or `Infinity`\n *\n * @example\n * const queue = asyncQueue<number>({ capacity: 100 })\n * await queue.put(42)\n * const value = await queue.take()\n */\nexport function asyncQueue<T>(options?: AsyncQueueOptions): AsyncQueue<T> {\n return new AsyncQueue<T>(options);\n}\n","/**\n * Go-style channels for CSP (Communicating Sequential Processes).\n *\n * This module gives typed, bidirectional communication channels inspired by Go.\n * Perfect for coordinating async operations and implementing concurrent patterns.\n *\n * @example\n * const ch = channel<number>()\n *\n * // Sender\n * await ch.send(42)\n *\n * // Receiver\n * const value = await ch.receive()\n *\n * // Select from multiple channels\n * const result = await select(\n * ch1.case((v) => console.log('ch1:', v)),\n * ch2.case((v) => console.log('ch2:', v))\n * )\n */\n\nimport { asyncQueue, type AsyncQueue } from \"./async-queue.js\";\n\n/**\n * Channel<T> - Bidirectional communication channel.\n *\n * The channels of Go are the model. This class gives send/receive operations\n * that can block until the other side is ready.\n *\n * @deprecated Import `Channel` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport class Channel<T> {\n private queue: AsyncQueue<T>;\n private _isClosed = false;\n\n constructor(bufferSize: number = 0) {\n // A buffer size of 0 is an unbuffered channel: send waits for a receiver (a rendezvous).\n // (Before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17.)\n this.queue = asyncQueue<T>({ capacity: bufferSize });\n }\n\n /**\n * This method sends a value through the channel.\n * The call blocks while the buffer of the channel is full.\n *\n * @throws Error if channel is closed\n */\n async send(value: T): Promise<void> {\n if (this._isClosed) {\n throw new Error(\"Cannot send on closed channel\");\n }\n await this.queue.put(value);\n }\n\n /**\n * This method receives a value from the channel.\n * The call blocks while no value is available.\n *\n * @throws Error if channel is closed and empty\n */\n async receive(): Promise<T> {\n return await this.queue.take();\n }\n\n /**\n * This method waits for one value, as `receive` does, and gives it to `onValue`. When the\n * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in\n * the call that sends the value or closes the channel.\n *\n * The function that it gives withdraws the wait, so no later value goes to it.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no value yet.\n */\n waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {\n return this.queue.waitTake(onValue, onClosed);\n }\n\n /**\n * This method tries to send without blocking.\n * This method gives false if channel is full.\n */\n trySend(value: T): boolean {\n if (this._isClosed) return false;\n return this.queue.tryPut(value);\n }\n\n /**\n * This method tries to receive without blocking.\n * This method gives undefined if no value is available.\n */\n tryReceive(): T | undefined {\n return this.queue.tryTake();\n }\n\n /**\n * This method closes the channel. No more values can be sent.\n * Receivers can still drain remaining values.\n */\n close(): void {\n this._isClosed = true;\n this.queue.close();\n }\n\n get isClosed(): boolean {\n return this._isClosed;\n }\n\n get size(): number {\n return this.queue.size;\n }\n\n /**\n * This method makes a select case for this channel.\n * The select() function uses this value for multiplexing.\n */\n case<R>(handler: (value: T) => R): SelectCase<R> {\n return {\n channel: this,\n handler,\n tryReceive: () => this.tryReceive(),\n receive: () => this.receive(),\n wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),\n };\n }\n\n /**\n * Async iteration over channel values.\n * Stops when channel is closed and empty.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n try {\n yield await this.receive();\n } catch (e) {\n // Channel closed\n break;\n }\n }\n }\n}\n\n/**\n * SelectCase represents a case in a select statement.\n *\n * @deprecated Import `SelectCase` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport interface SelectCase<R> {\n channel: Channel<any>;\n handler: (value: any) => R;\n tryReceive: () => any;\n receive: () => Promise<any>;\n /**\n * A wait for one value that `select` can withdraw: `Channel.waitReceive`. A case without it\n * uses the `waitReceive` method of its channel.\n */\n wait?: (onValue: (value: any) => void, onClosed: (error: Error) => void) => () => boolean;\n}\n\n/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */\ntype Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;\n\n/**\n * This function gives the first value of the waits, with the index of its wait. It rejects with\n * the error of the first wait whose channel is closed and empty. It withdraws each other wait in\n * the same call, so a later value stays in its channel. (Before, the receives of the cases that\n * lost stayed in their channels and dropped the next value of each: audit O56.)\n */\nfunction firstOf(waits: readonly Wait[]): Promise<{ index: number; value: unknown }> {\n return new Promise((resolve, reject) => {\n const withdraws: Array<() => boolean> = [];\n let settled = false;\n const end = (): void => {\n settled = true;\n for (const withdraw of withdraws) withdraw();\n };\n // A wait can call back at once, in its own call, when its channel has a value or is closed\n try {\n for (let index = 0; index < waits.length && !settled; index++) {\n withdraws.push(\n waits[index]!(\n (value) => {\n if (settled) return;\n end();\n resolve({ index, value });\n },\n (error) => {\n if (settled) return;\n end();\n reject(error);\n },\n ),\n );\n }\n } catch (error) {\n // A wait that throws: the waits before it are withdrawn\n if (!settled) end();\n reject(error);\n }\n });\n}\n\n/**\n * Selects from multiple channels (like Go's select statement).\n *\n * This function waits for the first channel to have a value available,\n * then calls its handler and gives the result.\n *\n * The first case with a value at once wins. The cases that lose keep no receive: a value that\n * comes later stays in its channel for the next receiver. When the channel of a case is closed\n * and empty, the given promise rejects.\n *\n * @example\n * const result = await select(\n * ch1.case((v) => `ch1: ${v}`),\n * ch2.case((v) => `ch2: ${v}`),\n * timeout(1000).case(() => 'timeout')\n * )\n *\n * @deprecated Import `select` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport async function select<R>(...cases: SelectCase<R>[]): Promise<R> {\n const { index, value } = await firstOf(\n cases.map((c): Wait => c.wait ?? ((onValue, onClosed) => c.channel.waitReceive(onValue, onClosed))),\n );\n // The handler runs after the race, not in the call of the sender\n return cases[index]!.handler(value);\n}\n\n/**\n * This function makes a timeout channel that sends after the specified duration.\n *\n * @example\n * const result = await select(\n * dataChannel.case((v) => v),\n * timeout(5000).case(() => 'timeout!')\n * )\n *\n * @deprecated Import `timeout` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function timeout(ms: number): Channel<void> {\n const ch = new Channel<void>();\n setTimeout(() => {\n ch.send(undefined).catch(() => {}); // Ignore if closed\n ch.close();\n }, ms);\n return ch;\n}\n\n/**\n * This function makes a ticker channel that sends at regular intervals.\n *\n * @example\n * const tick = ticker(1000) // Every second\n * for await (const t of tick) {\n * console.log('Tick:', t)\n * }\n *\n * @deprecated Import `ticker` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function ticker(ms: number): Channel<number> & { stop: () => void } {\n const ch = new Channel<number>(1);\n let count = 0;\n\n const intervalId = setInterval(() => {\n ch.trySend(count++);\n }, ms);\n\n return Object.assign(ch, {\n stop: () => {\n clearInterval(intervalId);\n ch.close();\n },\n });\n}\n\n/**\n * Pipeline: pipes values from input channel through transform to output channel.\n *\n * @example\n * const input = channel<number>()\n * const output = pipeline(input, (x) => x * 2)\n *\n * await input.send(5)\n * const result = await output.receive() // 10\n *\n * @deprecated Import `pipeline` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function pipeline<T, U>(\n input: Channel<T>,\n transform: (value: T) => U | Promise<U>,\n bufferSize: number = 0\n): Channel<U> {\n const output = new Channel<U>(bufferSize);\n\n // The output closes also when the transform fails, so its reader does not wait forever. The\n // error goes to the console, as in workerPool. (Before, it was an unhandled rejection: audit pass 2.)\n (async () => {\n try {\n for await (const value of input) {\n const transformed = await transform(value);\n await output.send(transformed);\n }\n } finally {\n output.close();\n }\n })().catch((error: unknown) => console.error(\"pipeline error:\", error));\n\n return output;\n}\n\n/**\n * Fan-out: distributes values from one input channel to multiple output channels.\n *\n * @example\n * const input = channel<number>()\n * const [out1, out2, out3] = fanOut(input, 3)\n *\n * // Each output gets a copy of every input value\n *\n * @deprecated Import `fanOut` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function fanOut<T>(input: Channel<T>, count: number, bufferSize: number = 0): Channel<T>[] {\n const outputs = Array.from({ length: count }, () => new Channel<T>(bufferSize));\n\n (async () => {\n try {\n for await (const value of input) {\n await Promise.all(outputs.map((ch) => ch.send(value)));\n }\n } finally {\n outputs.forEach((ch) => ch.close());\n }\n })().catch((error: unknown) => console.error(\"fanOut error:\", error));\n\n return outputs;\n}\n\n/**\n * Fan-in: this function merges multiple input channels into one output channel.\n *\n * @example\n * const ch1 = channel<number>()\n * const ch2 = channel<number>()\n * const merged = fanIn(ch1, ch2)\n *\n * // merged receives values from both ch1 and ch2\n *\n * @deprecated Import `fanIn` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function fanIn<T>(...inputs: Channel<T>[]): Channel<T> {\n const output = new Channel<T>();\n\n const workers = inputs.map(async (input) => {\n for await (const value of input) {\n await output.send(value);\n }\n });\n\n // All the workers settle, then the output closes, also after a failed send\n Promise.allSettled(workers).then((results) => {\n output.close();\n for (const result of results) if (result.status === \"rejected\") console.error(\"fanIn error:\", result.reason);\n });\n\n return output;\n}\n\n/**\n * Merge: like fanIn but closes output when first input closes.\n *\n * It takes one value at a time, from the inputs in turn. It keeps no receive on an input while\n * it waits for the reader of the output. Thus each value of each input reaches the output one\n * time, in the order of its input, or stays in its input.\n *\n * @deprecated Import `merge` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function merge<T>(...inputs: Channel<T>[]): Channel<T> {\n const output = new Channel<T>();\n\n (async () => {\n // The input after the input of the last value comes first, so a busy input starves no other\n let start = 0;\n while (true) {\n const order = inputs.map((_, offset) => (start + offset) % inputs.length);\n let next: { index: number; value: unknown };\n try {\n next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));\n } catch {\n // An input is closed and empty\n break;\n }\n const index = order[next.index]!;\n start = (index + 1) % inputs.length;\n try {\n await output.send(next.value as T);\n } catch {\n // The reader closed the output\n break;\n }\n }\n output.close();\n })();\n\n return output;\n}\n\n/**\n * Buffered channel with specified capacity.\n *\n * @deprecated Import `buffered` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function buffered<T>(capacity: number): Channel<T> {\n return new Channel<T>(capacity);\n}\n\n/**\n * Unbuffered channel (rendezvous point).\n * Sends block until receiver is ready.\n *\n * @deprecated Import `unbuffered` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function unbuffered<T>(): Channel<T> {\n return new Channel<T>(0);\n}\n\n/**\n * Factory function to make a channel.\n *\n * @example\n * const ch = channel<number>()\n * const bufferedCh = channel<string>(10)\n *\n * @deprecated Import `channel` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function channel<T>(bufferSize: number = 0): Channel<T> {\n return new Channel<T>(bufferSize);\n}\n\n/**\n * WorkerPool: distributes work across multiple workers.\n *\n * @example\n * const pool = workerPool(\n * jobChannel,\n * async (job) => await processJob(job),\n * { workers: 4 }\n * )\n *\n * // 4 workers concurrently process jobs from jobChannel\n *\n * @deprecated Import `workerPool` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function workerPool<T, R>(\n jobs: Channel<T>,\n worker: (job: T) => Promise<R>,\n options: { workers: number; bufferSize?: number } = { workers: 1 }\n): Channel<R> {\n const results = new Channel<R>(options.bufferSize || 0);\n const { workers: workerCount } = options;\n\n const workers = Array.from({ length: workerCount }, async () => {\n for await (const job of jobs) {\n try {\n const result = await worker(job);\n await results.send(result);\n } catch (error) {\n console.error(\"Worker error:\", error);\n }\n }\n });\n\n Promise.all(workers).then(() => results.close());\n\n return results;\n}\n","/**\n * asSettled - The results of running promises, in the order that they settle.\n *\n * @example\n * const pages = urls.map((url) => fetch(url));\n * for await (const result of asSettled(pages)) {\n * if (result.status === \"fulfilled\") show(result.index, result.value);\n * else report(result.index, result.reason);\n * }\n */\n\n/** One result of `asSettled`: the index of its promise in the input, and how the promise settled. */\nexport type Settled<T> = { readonly index: number } & PromiseSettledResult<T>;\n\n/**\n * This function gives the result of each promise when it settles, in settle order, not in input\n * order. The promises run already: this function starts nothing. Each result has the index of its\n * promise in the input. A rejected promise gives `status: \"rejected\"` and its reason: the\n * generator does not throw it. When the consumer stops early, the other promises continue, and\n * their rejections are not reported as unhandled.\n */\nexport async function* asSettled<T>(promises: Iterable<Promise<T>>): AsyncGenerator<Settled<T>, void, undefined> {\n const pending = new Map<number, Promise<Settled<T>>>();\n let next = 0;\n for (const promise of promises) {\n const index = next;\n next += 1;\n pending.set(\n index,\n Promise.resolve(promise).then(\n (value): Settled<T> => ({ index, status: \"fulfilled\", value }),\n (reason: unknown): Settled<T> => ({ index, status: \"rejected\", reason })\n )\n );\n }\n while (pending.size > 0) {\n const settled = await Promise.race(pending.values());\n pending.delete(settled.index);\n yield settled;\n }\n}\n","/**\n * semaphore - A bound on the tasks that run at the same time.\n *\n * @example\n * const writes = semaphore(4);\n * // At most 4 writes run at once. The others wait in the order that they came.\n * await Promise.all(items.map((item) => writes.run(() => store.set(item.id, item))));\n */\n\n/** A semaphore: a count of permits, and a queue of the callers that wait for one. */\nexport interface Semaphore {\n /** The permits of the semaphore. */\n readonly permits: number;\n /** The permits that no caller holds. */\n readonly available: number;\n /** The callers that wait for a permit. */\n readonly waiting: number;\n /**\n * This method gives a permit. It waits while all permits are held. The waiting callers get the permits in the order\n * that they came. The result is the release of the permit. A second call of the release does nothing.\n */\n acquire(): Promise<() => void>;\n /** This method starts a task with a permit. The permit goes back when the task ends, also when it throws. */\n run<R>(task: () => R | PromiseLike<R>): Promise<R>;\n}\n\n/**\n * This function makes a semaphore with `permits` permits. The value is a whole number of 1 or more, or `Infinity`\n * for no bound. Another value throws a `RangeError`.\n */\nexport function semaphore(permits: number): Semaphore {\n if (!(permits === Infinity || (Number.isInteger(permits) && permits >= 1))) {\n throw new RangeError(`A semaphore needs a whole number of permits of 1 or more, or Infinity: ${permits}`);\n }\n let held = 0;\n // The waiting callers, in the order that they came. A release gives its permit to the first.\n const queue: Array<() => void> = [];\n let head = 0;\n\n const releaseOnce = (): (() => void) => {\n let done = false;\n return () => {\n if (done) return;\n done = true;\n if (head < queue.length) {\n const next = queue[head]!;\n head += 1;\n // The permit goes from the releaser to the next caller, so `held` does not change\n if (head > 64 && head * 2 > queue.length) {\n queue.splice(0, head);\n head = 0;\n }\n next();\n } else {\n held -= 1;\n }\n };\n };\n\n const acquire = (): Promise<() => void> => {\n if (held < permits) {\n held += 1;\n return Promise.resolve(releaseOnce());\n }\n return new Promise((resolve) => {\n queue.push(() => resolve(releaseOnce()));\n });\n };\n\n return {\n permits,\n get available() {\n return permits - held;\n },\n get waiting() {\n return queue.length - head;\n },\n acquire,\n async run<R>(task: () => R | PromiseLike<R>): Promise<R> {\n const release = await acquire();\n try {\n return await task();\n } finally {\n release();\n }\n },\n };\n}\n","/**\n * Functional operations for iterables (lazy sync transforms).\n *\n * This module gives Stream-like operations with lazy evaluation.\n * All operations return generators for composability.\n *\n * @example\n * const result = pipe(\n * [1, 2, 3, 4, 5],\n * (it) => map(it, x => x * 2),\n * (it) => filter(it, x => x > 5),\n * (it) => take(it, 2),\n * toArray\n * ) // [6, 8]\n */\n\n// ============================================================================\n// Mapping and transformation\n// ============================================================================\n\n/**\n * This function maps each element through a function.\n *\n * @example\n * const doubled = map([1, 2, 3], x => x * 2) // [2, 4, 6]\n */\nexport function* map<T, U>(\n iterable: Iterable<T>,\n fn: (value: T, index: number) => U\n): Generator<U> {\n let index = 0;\n for (const value of iterable) {\n yield fn(value, index++);\n }\n}\n\n/**\n * This function filters elements based on a predicate.\n */\nexport function* filter<T>(\n iterable: Iterable<T>,\n predicate: (value: T, index: number) => boolean\n): Generator<T> {\n let index = 0;\n for (const value of iterable) {\n if (predicate(value, index++)) {\n yield value;\n }\n }\n}\n\n/**\n * This function flatMaps each element to an iterable and flattens.\n */\nexport function* flatMap<T, U>(\n iterable: Iterable<T>,\n fn: (value: T, index: number) => Iterable<U>\n): Generator<U> {\n let index = 0;\n for (const value of iterable) {\n yield* fn(value, index++);\n }\n}\n\n/**\n * This function flattens a nested iterable.\n */\nexport function* flatten<T>(iterable: Iterable<Iterable<T>>): Generator<T> {\n for (const inner of iterable) {\n yield* inner;\n }\n}\n\n// ============================================================================\n// Limiting and skipping\n// ============================================================================\n\n/**\n * This function takes the first n elements. It reads no element after the n-th one, and it reads nothing when n is 0.\n */\nexport function* take<T>(iterable: Iterable<T>, n: number): Generator<T> {\n if (n <= 0) return;\n let count = 0;\n for (const value of iterable) {\n yield value;\n if (++count >= n) return;\n }\n}\n\n/**\n * This function skips the first n elements.\n */\nexport function* skip<T>(iterable: Iterable<T>, n: number): Generator<T> {\n let count = 0;\n for (const value of iterable) {\n if (count++ >= n) {\n yield value;\n }\n }\n}\n\n/**\n * This function takes elements while predicate is true.\n */\nexport function* takeWhile<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): Generator<T> {\n for (const value of iterable) {\n if (!predicate(value)) break;\n yield value;\n }\n}\n\n/**\n * This function skips elements while predicate is true.\n */\nexport function* skipWhile<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): Generator<T> {\n let skipping = true;\n for (const value of iterable) {\n if (skipping && predicate(value)) continue;\n skipping = false;\n yield value;\n }\n}\n\n// ============================================================================\n// Combining\n// ============================================================================\n\n/**\n * Concatenates multiple iterables.\n */\nexport function* concat<T>(...iterables: Iterable<T>[]): Generator<T> {\n for (const iterable of iterables) {\n yield* iterable;\n }\n}\n\n/**\n * Zips multiple iterables together.\n */\nexport function* zip<T extends any[]>(\n ...iterables: { [K in keyof T]: Iterable<T[K]> }\n): Generator<T> {\n const iterators = iterables.map((it) => it[Symbol.iterator]());\n\n while (true) {\n const results = iterators.map((it) => it.next());\n if (results.some((r) => r.done)) break;\n yield results.map((r) => r.value) as T;\n }\n}\n\n/**\n * Zips with index.\n */\nexport function* enumerate<T>(iterable: Iterable<T>): Generator<[number, T]> {\n let index = 0;\n for (const value of iterable) {\n yield [index++, value];\n }\n}\n\n// ============================================================================\n// Partitioning\n// ============================================================================\n\n/**\n * Chunks elements into arrays of specified size.\n */\nexport function* chunk<T>(iterable: Iterable<T>, size: number): Generator<T[]> {\n let chunk: T[] = [];\n for (const value of iterable) {\n chunk.push(value);\n if (chunk.length === size) {\n yield chunk;\n chunk = [];\n }\n }\n if (chunk.length > 0) {\n yield chunk;\n }\n}\n\n/**\n * This function makes a sliding window of specified size.\n */\nexport function* window<T>(iterable: Iterable<T>, size: number): Generator<T[]> {\n const window: T[] = [];\n for (const value of iterable) {\n window.push(value);\n if (window.length > size) {\n window.shift();\n }\n if (window.length === size) {\n yield [...window];\n }\n }\n}\n\n/**\n * Partitions elements into two arrays based on predicate.\n */\nexport function partition<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): [T[], T[]] {\n const truthy: T[] = [];\n const falsy: T[] = [];\n\n for (const value of iterable) {\n if (predicate(value)) {\n truthy.push(value);\n } else {\n falsy.push(value);\n }\n }\n\n return [truthy, falsy];\n}\n\n// ============================================================================\n// Reducing and folding\n// ============================================================================\n\n/**\n * This function reduces iterable to a single value.\n */\nexport function reduce<T, U>(\n iterable: Iterable<T>,\n fn: (acc: U, value: T, index: number) => U,\n initial: U\n): U {\n let acc = initial;\n let index = 0;\n for (const value of iterable) {\n acc = fn(acc, value, index++);\n }\n return acc;\n}\n\n/**\n * Scans (like reduce but emits intermediate results).\n */\nexport function* scan<T, U>(\n iterable: Iterable<T>,\n fn: (acc: U, value: T) => U,\n initial: U\n): Generator<U> {\n let acc = initial;\n yield acc;\n for (const value of iterable) {\n acc = fn(acc, value);\n yield acc;\n }\n}\n\n// ============================================================================\n// Sorting and ordering\n// ============================================================================\n\n/**\n * This function sorts elements (materializes the iterable).\n */\nexport function* sort<T>(\n iterable: Iterable<T>,\n compare?: (a: T, b: T) => number\n): Generator<T> {\n const array = Array.from(iterable);\n array.sort(compare);\n yield* array;\n}\n\n/**\n * Reverses elements (materializes the iterable).\n */\nexport function* reverse<T>(iterable: Iterable<T>): Generator<T> {\n const array = Array.from(iterable);\n array.reverse();\n yield* array;\n}\n\n// ============================================================================\n// Distinct and uniqueness\n// ============================================================================\n\n/**\n * This function removes duplicate elements (by reference or key function).\n */\nexport function* distinct<T, K = T>(\n iterable: Iterable<T>,\n keyFn?: (value: T) => K\n): Generator<T> {\n const seen = new Set<K>();\n for (const value of iterable) {\n const key = (keyFn ? keyFn(value) : value) as K;\n if (!seen.has(key)) {\n seen.add(key);\n yield value;\n }\n }\n}\n\n/**\n * This function removes consecutive duplicates.\n */\nexport function* distinctConsecutive<T, K = T>(\n iterable: Iterable<T>,\n keyFn?: (value: T) => K\n): Generator<T> {\n let lastKey: K | undefined;\n let first = true;\n\n for (const value of iterable) {\n const key = (keyFn ? keyFn(value) : value) as K;\n if (first || key !== lastKey) {\n yield value;\n lastKey = key;\n first = false;\n }\n }\n}\n\n// ============================================================================\n// Peeking and side effects\n// ============================================================================\n\n/**\n * This function does a side effect for each element. The stream does not change.\n */\nexport function* tap<T>(\n iterable: Iterable<T>,\n fn: (value: T, index: number) => void\n): Generator<T> {\n let index = 0;\n for (const value of iterable) {\n fn(value, index++);\n yield value;\n }\n}\n\n// ============================================================================\n// Predicates and checks\n// ============================================================================\n\n/**\n * This function gives true if any element matches the predicate.\n */\nexport function some<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): boolean {\n for (const value of iterable) {\n if (predicate(value)) return true;\n }\n return false;\n}\n\n/**\n * This function gives true if all elements match the predicate.\n */\nexport function every<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): boolean {\n for (const value of iterable) {\n if (!predicate(value)) return false;\n }\n return true;\n}\n\n/**\n * This function gives true if no elements match the predicate.\n */\nexport function none<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): boolean {\n return !some(iterable, predicate);\n}\n\n/**\n * This function finds the first element matching the predicate.\n */\nexport function find<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): T | undefined {\n for (const value of iterable) {\n if (predicate(value)) return value;\n }\n return undefined;\n}\n\n/**\n * This function counts elements (optionally matching a predicate).\n */\nexport function count<T>(\n iterable: Iterable<T>,\n predicate?: (value: T) => boolean\n): number {\n let count = 0;\n for (const value of iterable) {\n if (!predicate || predicate(value)) {\n count++;\n }\n }\n return count;\n}\n\n// ============================================================================\n// Min/Max\n// ============================================================================\n\n/**\n * This function gives the minimum element.\n */\nexport function min<T>(\n iterable: Iterable<T>,\n compare?: (a: T, b: T) => number\n): T | undefined {\n const cmp = compare || ((a: any, b: any) => a - b);\n let minValue: T | undefined;\n\n for (const value of iterable) {\n if (minValue === undefined || cmp(value, minValue) < 0) {\n minValue = value;\n }\n }\n\n return minValue;\n}\n\n/**\n * This function gives the maximum element.\n */\nexport function max<T>(\n iterable: Iterable<T>,\n compare?: (a: T, b: T) => number\n): T | undefined {\n const cmp = compare || ((a: any, b: any) => a - b);\n let maxValue: T | undefined;\n\n for (const value of iterable) {\n if (maxValue === undefined || cmp(value, maxValue) > 0) {\n maxValue = value;\n }\n }\n\n return maxValue;\n}\n\n/**\n * This function gives the sum of elements.\n */\nexport function sum(iterable: Iterable<number>): number {\n let total = 0;\n for (const value of iterable) {\n total += value;\n }\n return total;\n}\n\n/**\n * This function gives the average of elements.\n */\nexport function average(iterable: Iterable<number>): number | undefined {\n let total = 0;\n let count = 0;\n\n for (const value of iterable) {\n total += value;\n count++;\n }\n\n return count === 0 ? undefined : total / count;\n}\n\n// ============================================================================\n// Terminal operations (materialization)\n// ============================================================================\n\n/**\n * This function collects elements into an array.\n */\nexport function toArray<T>(iterable: Iterable<T>): T[] {\n return Array.from(iterable);\n}\n\n/**\n * This function collects elements into a Set.\n */\nexport function toSet<T>(iterable: Iterable<T>): Set<T> {\n return new Set(iterable);\n}\n\n/**\n * This function collects elements into a Map.\n */\nexport function toMap<T, K, V>(\n iterable: Iterable<T>,\n keyFn: (value: T) => K,\n valueFn: (value: T) => V\n): Map<K, V> {\n const map = new Map<K, V>();\n for (const value of iterable) {\n map.set(keyFn(value), valueFn(value));\n }\n return map;\n}\n\n// ============================================================================\n// Pipe utility for composition\n// ============================================================================\n\n/**\n * This function pipes a value through a series of transformations.\n *\n * @example\n * const result = pipe(\n * [1, 2, 3, 4, 5],\n * (it) => map(it, x => x * 2),\n * (it) => filter(it, x => x > 5),\n * (it) => take(it, 2),\n * toArray\n * ) // [6, 8]\n */\nexport function pipe<T>(\n value: T,\n ...fns: Array<(value: any) => any>\n): any {\n return fns.reduce((acc, fn) => fn(acc), value);\n}\n","/**\n * Collectors for Stream-style collection operations.\n *\n * This module gives Java Stream API-style collectors for transforming iterables\n * into various collection types. The model is java.util.stream.Collectors.\n *\n * @example\n * import { collect, toList, groupingBy } from './collectors'\n *\n * const grouped = collect(users, groupingBy(u => u.age))\n */\n\nimport { arrayList, type ArrayList } from \"../impl/array-list.js\";\nimport { hashMap, type HashMap } from \"../impl/hash-map.js\";\nimport { hashSet, type HashSet } from \"../impl/hash-set.js\";\n\n// ============================================================================\n// Collector interface\n// ============================================================================\n\n/**\n * A Collector represents a mutable reduction operation.\n *\n * @template T - The type of input elements\n * @template A - The mutable accumulation type\n * @template R - The final result type\n */\nexport interface Collector<T, A, R> {\n /**\n * This value makes the initial accumulator.\n */\n supplier: () => A;\n\n /**\n * This value incorporates an element into the accumulator and gives the next accumulator. A mutable\n * accumulator (a list, a map) gives itself. An immutable one (a count, a sum) gives the\n * new value. (Before, the result was ignored, so every immutable collector - counting,\n * summing, minBy, maxBy, reducing, first, last - given its seed: BUGS-2026-07 C12.)\n */\n accumulator: (acc: A, element: T) => A;\n\n /**\n * This value combines two accumulators (for parallel streams).\n */\n combiner?: (acc1: A, acc2: A) => A;\n\n /**\n * This value transforms the accumulator into the final result.\n */\n finisher: (acc: A) => R;\n}\n\n/**\n * This function collects elements using a collector.\n *\n * @example\n * const list = collect([1, 2, 3], toList())\n * const set = collect([1, 2, 2, 3], toSet())\n */\nexport function collect<T, A, R>(\n iterable: Iterable<T>,\n collector: Collector<T, A, R>\n): R {\n let acc = collector.supplier();\n for (const element of iterable) {\n acc = collector.accumulator(acc, element);\n }\n return collector.finisher(acc);\n}\n\n// ============================================================================\n// Basic collectors\n// ============================================================================\n\n/**\n * This function collects elements into an ArrayList.\n */\nexport function toList<T>(): Collector<T, ArrayList<T>, ArrayList<T>> {\n return {\n supplier: () => arrayList<T>(),\n accumulator: (list, element) => (list.add(element), list),\n finisher: (list) => list,\n };\n}\n\n/**\n * This function collects elements into a HashSet.\n */\nexport function toSet<T>(): Collector<T, HashSet<T>, HashSet<T>> {\n return {\n supplier: () => hashSet<T>(),\n accumulator: (set, element) => (set.add(element), set),\n finisher: (set) => set,\n };\n}\n\n/**\n * This function collects elements into a native Array.\n */\nexport function toArray<T>(): Collector<T, T[], T[]> {\n return {\n supplier: () => [],\n accumulator: (arr, element) => (arr.push(element), arr),\n finisher: (arr) => arr,\n };\n}\n\n/**\n * This function collects elements into a HashMap using key and value extractors.\n */\nexport function toMap<T, K, V>(\n keyExtractor: (element: T) => K,\n valueExtractor: (element: T) => V\n): Collector<T, HashMap<K, V>, HashMap<K, V>> {\n return {\n supplier: () => hashMap<K, V>(),\n accumulator: (map, element) => {\n map.set(keyExtractor(element), valueExtractor(element));\n return map;\n },\n finisher: (map) => map,\n };\n}\n\n// ============================================================================\n// Grouping collectors\n// ============================================================================\n\n/**\n * This function groups elements by a classifier function.\n *\n * @example\n * const byAge = collect(users, groupingBy(u => u.age))\n * // Map<number, ArrayList<User>>\n */\nexport function groupingBy<T, K>(\n classifier: (element: T) => K\n): Collector<T, HashMap<K, ArrayList<T>>, HashMap<K, ArrayList<T>>> {\n return {\n supplier: () => hashMap<K, ArrayList<T>>(),\n accumulator: (map, element) => {\n const key = classifier(element);\n const list = map.computeIfAbsent(key, () => arrayList<T>());\n list.add(element);\n return map;\n },\n finisher: (map) => map,\n };\n}\n\n/**\n * This function groups the elements and transforms each group with a downstream collector.\n *\n * @example\n * const countByAge = collect(\n * users,\n * groupingBy(u => u.age, counting())\n * )\n * // Map<number, number>\n */\nexport function groupingByWith<T, K, A, D>(\n classifier: (element: T) => K,\n downstream: Collector<T, A, D>\n): Collector<T, HashMap<K, A>, HashMap<K, D>> {\n return {\n supplier: () => hashMap<K, A>(),\n accumulator: (map, element) => {\n const key = classifier(element);\n const acc = map.has(key) ? map.get(key) : downstream.supplier();\n map.set(key, downstream.accumulator(acc, element));\n return map;\n },\n finisher: (map) => {\n const result = hashMap<K, D>();\n for (const entry of map.entries()) {\n result.set(entry.key, downstream.finisher(entry.value));\n }\n return result;\n },\n };\n}\n\n/**\n * Partitions elements into two groups based on a predicate.\n *\n * @example\n * const partitioned = collect(\n * numbers,\n * partitioningBy(n => n % 2 === 0)\n * )\n * // Map<boolean, ArrayList<number>>\n */\nexport function partitioningBy<T>(\n predicate: (element: T) => boolean\n): Collector<T, HashMap<boolean, ArrayList<T>>, HashMap<boolean, ArrayList<T>>> {\n return groupingBy((element) => predicate(element));\n}\n\n// ============================================================================\n// Aggregation collectors\n// ============================================================================\n\n/**\n * This function counts the number of elements.\n */\nexport function counting<T>(): Collector<T, number, number> {\n return {\n supplier: () => 0,\n accumulator: (count) => count + 1,\n finisher: (count) => count,\n };\n}\n\n/**\n * Sums numeric elements.\n */\nexport function summingNumber<T>(\n mapper: (element: T) => number\n): Collector<T, number, number> {\n return {\n supplier: () => 0,\n accumulator: (sum, element) => sum + mapper(element),\n finisher: (sum) => sum,\n };\n}\n\n/**\n * Averages numeric elements.\n */\nexport function averagingNumber<T>(\n mapper: (element: T) => number\n): Collector<T, { sum: number; count: number }, number> {\n return {\n supplier: () => ({ sum: 0, count: 0 }),\n accumulator: (acc, element) => {\n acc.sum += mapper(element);\n acc.count++;\n return acc;\n },\n finisher: (acc) => (acc.count === 0 ? 0 : acc.sum / acc.count),\n };\n}\n\n/**\n * This function finds the minimum element.\n */\nexport function minBy<T>(\n comparator: (a: T, b: T) => number\n): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (min, element) => {\n if (min === undefined || comparator(element, min) < 0) {\n return element;\n }\n return min;\n },\n finisher: (min) => min,\n };\n}\n\n/**\n * This function finds the maximum element.\n */\nexport function maxBy<T>(\n comparator: (a: T, b: T) => number\n): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (max, element) => {\n if (max === undefined || comparator(element, max) > 0) {\n return element;\n }\n return max;\n },\n finisher: (max) => max,\n };\n}\n\n// ============================================================================\n// String collectors\n// ============================================================================\n\n/**\n * Joins elements into a string.\n *\n * @example\n * const csv = collect(['a', 'b', 'c'], joining(', '))\n * // \"a, b, c\"\n *\n * const bracketed = collect(\n * ['a', 'b', 'c'],\n * joining(', ', '[', ']')\n * )\n * // \"[a, b, c]\"\n */\nexport function joining<T>(\n delimiter: string = \"\",\n prefix: string = \"\",\n suffix: string = \"\"\n): Collector<T, string[], string> {\n return {\n supplier: () => [],\n accumulator: (parts, element) => (parts.push(String(element)), parts),\n finisher: (parts) => prefix + parts.join(delimiter) + suffix,\n };\n}\n\n// ============================================================================\n// Mapping collectors\n// ============================================================================\n\n/**\n * This function applies a mapping function before collecting.\n *\n * @example\n * const names = collect(\n * users,\n * mapping(u => u.name, toList())\n * )\n */\nexport function mapping<T, U, A, R>(\n mapper: (element: T) => U,\n downstream: Collector<U, A, R>\n): Collector<T, A, R> {\n return {\n supplier: downstream.supplier,\n accumulator: (acc, element) => downstream.accumulator(acc, mapper(element)),\n finisher: downstream.finisher,\n };\n}\n\n/**\n * This function filters elements before collecting.\n */\nexport function filtering<T, A, R>(\n predicate: (element: T) => boolean,\n downstream: Collector<T, A, R>\n): Collector<T, A, R> {\n return {\n supplier: downstream.supplier,\n accumulator: (acc, element) => {\n return predicate(element) ? downstream.accumulator(acc, element) : acc;\n },\n finisher: downstream.finisher,\n };\n}\n\n/**\n * FlatMaps elements before collecting.\n */\nexport function flatMapping<T, U, A, R>(\n mapper: (element: T) => Iterable<U>,\n downstream: Collector<U, A, R>\n): Collector<T, A, R> {\n return {\n supplier: downstream.supplier,\n accumulator: (acc, element) => {\n for (const mapped of mapper(element)) {\n acc = downstream.accumulator(acc, mapped);\n }\n return acc;\n },\n finisher: downstream.finisher,\n };\n}\n\n// ============================================================================\n// Reducing collectors\n// ============================================================================\n\n/**\n * General reduction collector.\n */\nexport function reducing<T>(\n identity: T,\n reducer: (acc: T, element: T) => T\n): Collector<T, T, T> {\n return {\n supplier: () => identity,\n accumulator: (acc, element) => reducer(acc, element),\n finisher: (acc) => acc,\n };\n}\n\n/**\n * Reducing with mapper.\n */\nexport function reducingWith<T, U>(\n identity: U,\n mapper: (element: T) => U,\n reducer: (acc: U, mapped: U) => U\n): Collector<T, U, U> {\n return {\n supplier: () => identity,\n accumulator: (acc, element) => reducer(acc, mapper(element)),\n finisher: (acc) => acc,\n };\n}\n\n// ============================================================================\n// Composite collectors\n// ============================================================================\n\n/**\n * This function collects with two collectors and combines results.\n *\n * @example\n * const stats = collect(\n * numbers,\n * teeing(\n * summingNumber(n => n),\n * counting(),\n * (sum, count) => ({ sum, count, avg: sum / count })\n * )\n * )\n */\nexport function teeing<T, A1, A2, R1, R2, R>(\n collector1: Collector<T, A1, R1>,\n collector2: Collector<T, A2, R2>,\n combiner: (r1: R1, r2: R2) => R\n): Collector<T, [A1, A2], R> {\n return {\n supplier: () => [collector1.supplier(), collector2.supplier()] as [A1, A2],\n accumulator: ([acc1, acc2], element) => [\n collector1.accumulator(acc1, element),\n collector2.accumulator(acc2, element),\n ],\n finisher: ([acc1, acc2]) => {\n return combiner(collector1.finisher(acc1), collector2.finisher(acc2));\n },\n };\n}\n\n// ============================================================================\n// Utility collectors\n// ============================================================================\n\n/**\n * This function collects the first element.\n */\nexport function first<T>(): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (first, element) => (first === undefined ? element : first),\n finisher: (first) => first,\n };\n}\n\n/**\n * This function collects the last element.\n */\nexport function last<T>(): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (_last, element) => element,\n finisher: (last) => last,\n };\n}\n\n/**\n * This type makes summary statistics.\n */\nexport interface SummaryStatistics {\n count: number;\n sum: number;\n min: number;\n max: number;\n average: number;\n}\n\nexport function summarizingNumber<T>(\n mapper: (element: T) => number\n): Collector<T, Partial<SummaryStatistics>, SummaryStatistics> {\n return {\n supplier: () => ({\n count: 0,\n sum: 0,\n min: Infinity,\n max: -Infinity,\n }),\n accumulator: (stats, element) => {\n const value = mapper(element);\n // The supplier sets every field. (Before, `stats.min || Infinity` treated a minimum of 0\n // as missing: BUGS-2026-07 L16.)\n stats.count = stats.count! + 1;\n stats.sum = stats.sum! + value;\n stats.min = Math.min(stats.min!, value);\n stats.max = Math.max(stats.max!, value);\n return stats;\n },\n finisher: (stats) => ({\n count: stats.count!,\n sum: stats.sum!,\n min: stats.min!,\n max: stats.max!,\n average: stats.count! === 0 ? 0 : stats.sum! / stats.count!,\n }),\n };\n}\n","/**\n * Factory utilities for making collections.\n *\n * This module gives convenient factory methods similar to Java's Collections class.\n * These functions mirror Java methods like Collections.emptyList() and singletonList().\n */\n\nimport { arrayList, ArrayList } from \"../impl/array-list.js\";\nimport { arrayDeque, ArrayDeque } from \"../impl/array-deque.js\";\nimport { hashMap, HashMap } from \"../impl/hash-map.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue } from \"../interfaces/queue.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { readonly } from \"../behaviors/readonly.js\";\nimport { compose } from \"../core/middleware.js\";\n\n// ============================================================================\n// Empty collections\n// ============================================================================\n\n/**\n * This value is an empty, immutable list.\n * Multiple calls return the same instance (singleton pattern).\n *\n * @example\n * const list = emptyList<number>()\n * list.size // 0\n * list.add(1) // Error: Cannot modify readonly collection\n */\nconst EMPTY_LIST_CACHE = new Map<any, any>();\n\nexport function emptyList<T>(): List<T> {\n const key = \"list\";\n if (!EMPTY_LIST_CACHE.has(key)) {\n const list = compose(readonly<List<T>>())(arrayList<T>());\n EMPTY_LIST_CACHE.set(key, list);\n }\n return EMPTY_LIST_CACHE.get(key);\n}\n\n/**\n * This value is an empty, immutable queue.\n */\nconst EMPTY_QUEUE_CACHE = new Map<any, any>();\n\nexport function emptyQueue<T>(): Queue<T> {\n const key = \"queue\";\n if (!EMPTY_QUEUE_CACHE.has(key)) {\n const queue = compose(readonly<Queue<T>>())(arrayDeque<T>() as Queue<T>);\n EMPTY_QUEUE_CACHE.set(key, queue);\n }\n return EMPTY_QUEUE_CACHE.get(key);\n}\n\n/**\n * This value is an empty, immutable map.\n */\nconst EMPTY_MAP_CACHE = new Map<any, any>();\n\nexport function emptyMap<K, V>(): MapLike<K, V> {\n const key = \"map\";\n if (!EMPTY_MAP_CACHE.has(key)) {\n const map = compose(readonly<MapLike<K, V>>())(hashMap<K, V>());\n EMPTY_MAP_CACHE.set(key, map);\n }\n return EMPTY_MAP_CACHE.get(key);\n}\n\n// ============================================================================\n// Singleton collections (single element)\n// ============================================================================\n\n/**\n * This function gives an immutable list containing only the specified element.\n *\n * @example\n * const list = singletonList(42)\n * list.size // 1\n * list.get(0) // 42\n * list.add(2) // Error: Cannot modify readonly collection\n */\nexport function singletonList<T>(element: T): List<T> {\n const list = arrayList<T>();\n list.add(element);\n return compose(readonly<List<T>>())(list);\n}\n\n/**\n * This function gives an immutable map containing only the specified key-value mapping.\n */\nexport function singletonMap<K, V>(key: K, value: V): MapLike<K, V> {\n const map = hashMap<K, V>();\n map.set(key, value);\n return compose(readonly<MapLike<K, V>>())(map);\n}\n\n// ============================================================================\n// N-copies collections\n// ============================================================================\n\n/**\n * This function gives an immutable list consisting of n copies of the specified element.\n *\n * @example\n * const list = nCopies(5, 'hello')\n * list.size // 5\n * list.get(2) // 'hello'\n */\nexport function nCopies<T>(n: number, element: T): List<T> {\n if (n < 0) {\n throw new Error(`n must be non-negative, got ${n}`);\n }\n\n const list = arrayList<T>();\n for (let i = 0; i < n; i++) {\n list.add(element);\n }\n return compose(readonly<List<T>>())(list);\n}\n\n// ============================================================================\n// Collection creation from iterables\n// ============================================================================\n\n/**\n * This function makes a new ArrayList from the given elements.\n *\n * @example\n * const list = listOf(1, 2, 3, 4, 5)\n */\nexport function listOf<T>(...elements: T[]): ArrayList<T> {\n return arrayList(elements);\n}\n\n/**\n * This function makes a new ArrayDeque from the given elements.\n */\nexport function queueOf<T>(...elements: T[]): ArrayDeque<T> {\n return arrayDeque(elements);\n}\n\n/**\n * This function makes a new HashMap from the given key-value pairs.\n *\n * @example\n * const map = mapOf(['a', 1], ['b', 2], ['c', 3])\n */\nexport function mapOf<K, V>(...entries: [K, V][]): HashMap<K, V> {\n return hashMap(entries);\n}\n\n// ============================================================================\n// Mutable collection factories\n// ============================================================================\n\n/**\n * This function makes a new mutable ArrayList with optional initial elements.\n *\n * @example\n * const list = mutableListOf(1, 2, 3)\n * list.add(4)\n */\nexport function mutableListOf<T>(...elements: T[]): ArrayList<T> {\n return arrayList(elements);\n}\n\n/**\n * This function makes a new mutable HashMap with optional initial entries.\n */\nexport function mutableMapOf<K, V>(...entries: [K, V][]): HashMap<K, V> {\n return hashMap(entries);\n}\n\n// ============================================================================\n// Immutable collection factories\n// ============================================================================\n\n/**\n * This function makes an immutable List from the given elements.\n *\n * @example\n * const list = immutableListOf(1, 2, 3)\n * list.get(0) // 1\n * list.add(4) // Error: Cannot modify readonly collection\n */\nexport function immutableListOf<T>(...elements: T[]): List<T> {\n if (elements.length === 0) {\n return emptyList<T>();\n }\n if (elements.length === 1) {\n return singletonList(elements[0]! as T);\n }\n const list = arrayList(elements);\n return compose(readonly<List<T>>())(list);\n}\n\n/**\n * This function makes an immutable Map from the given entries.\n */\nexport function immutableMapOf<K, V>(...entries: [K, V][]): MapLike<K, V> {\n if (entries.length === 0) {\n return emptyMap<K, V>();\n }\n if (entries.length === 1) {\n return singletonMap(entries[0]![0], entries[0]![1]);\n }\n const map = hashMap(entries);\n return compose(readonly<MapLike<K, V>>())(map);\n}\n\n// ============================================================================\n// Range factories\n// ============================================================================\n\n/**\n * This function makes a list containing integers from start (inclusive) to end (exclusive).\n *\n * @example\n * const list = range(0, 5) // [0, 1, 2, 3, 4]\n * const list2 = range(10, 15) // [10, 11, 12, 13, 14]\n */\nexport function range(start: number, end: number, step: number = 1): ArrayList<number> {\n if (step === 0) {\n throw new Error(\"step cannot be zero\");\n }\n\n const list = arrayList<number>();\n\n if (step > 0) {\n for (let i = start; i < end; i += step) {\n list.add(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n list.add(i);\n }\n }\n\n return list;\n}\n\n/**\n * This function makes a list containing integers from 0 to n (exclusive).\n *\n * @example\n * const list = rangeTo(5) // [0, 1, 2, 3, 4]\n */\nexport function rangeTo(n: number): ArrayList<number> {\n return range(0, n);\n}\n\n// ============================================================================\n// Collection builders\n// ============================================================================\n\n/**\n * Builder for constructing lists with a fluent API.\n *\n * @example\n * const list = buildList<number>((builder) => {\n * builder.add(1)\n * builder.add(2)\n * if (someCondition) {\n * builder.add(3)\n * }\n * })\n */\nexport function buildList<T>(builder: (list: ArrayList<T>) => void): ArrayList<T> {\n const list = arrayList<T>();\n builder(list);\n return list;\n}\n\n/**\n * Builder for constructing maps with a fluent API.\n */\nexport function buildMap<K, V>(builder: (map: HashMap<K, V>) => void): HashMap<K, V> {\n const map = hashMap<K, V>();\n builder(map);\n return map;\n}\n\n// ============================================================================\n// Conversion utilities\n// ============================================================================\n\n/**\n * This function converts an iterable to an ArrayList.\n *\n * @example\n * const set = new Set([1, 2, 3])\n * const list = toList(set)\n */\nexport function toList<T>(iterable: Iterable<T>): ArrayList<T> {\n return arrayList(iterable);\n}\n\n/**\n * This function converts an iterable to a HashMap using a key extractor function.\n *\n * @example\n * const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]\n * const userMap = toMap(users, u => u.id)\n */\nexport function toMap<T, K>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K\n): HashMap<K, T>;\nexport function toMap<T, K, V>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K,\n valueExtractor: (value: T) => V\n): HashMap<K, V>;\nexport function toMap<T, K, V>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K,\n valueExtractor?: (value: T) => V\n): HashMap<K, any> {\n const map = hashMap<K, any>();\n for (const item of iterable) {\n const key = keyExtractor(item);\n const value = valueExtractor ? valueExtractor(item) : item;\n map.set(key, value);\n }\n return map;\n}\n\n// ============================================================================\n// Grouping utilities\n// ============================================================================\n\n/**\n * This function groups elements by a key extractor function.\n *\n * @example\n * const users = [\n * { age: 25, name: 'Alice' },\n * { age: 30, name: 'Bob' },\n * { age: 25, name: 'Charlie' }\n * ]\n * const byAge = groupBy(users, u => u.age)\n * // Map { 25 => [Alice, Charlie], 30 => [Bob] }\n */\nexport function groupBy<T, K>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K\n): HashMap<K, ArrayList<T>> {\n const map = hashMap<K, ArrayList<T>>();\n\n for (const item of iterable) {\n const key = keyExtractor(item);\n const list = map.computeIfAbsent(key, () => arrayList<T>());\n list.add(item);\n }\n\n return map;\n}\n","/**\n * Common helper utilities for collections.\n *\n * This module gives shared functionality to reduce code duplication across implementations.\n */\n\nimport type { Eq } from \"../core/traits.js\";\n\n// ============================================================================\n// Bounds checking utilities\n// ============================================================================\n\n/**\n * This function gives true when an index is in the bounds [0, size).\n * This function throws RangeError if out of bounds.\n *\n * @param index The index to check\n * @param size The size of the collection\n * @param collectionName Optional name for error message\n * @throws RangeError if index is out of bounds\n */\nexport function checkBounds(index: number, size: number, collectionName: string = \"Collection\"): void {\n if (index < 0 || index >= size) {\n throw new RangeError(`${collectionName}: Index ${index} out of bounds [0, ${size})`);\n }\n}\n\n/**\n * This function gives true when an index is valid for an insertion, in [0, size].\n * In this function, index === size is correct for append operations.\n *\n * @param index The index to check\n * @param size The size of the collection\n * @param collectionName Optional name for error message\n * @throws RangeError if index is out of bounds\n */\nexport function checkInsertBounds(index: number, size: number, collectionName: string = \"Collection\"): void {\n if (index < 0 || index > size) {\n throw new RangeError(`${collectionName}: Index ${index} out of bounds [0, ${size}]`);\n }\n}\n\n/**\n * This function gives true when a range [start, end) is valid.\n *\n * @param start Start index (inclusive)\n * @param end End index (exclusive)\n * @param size The size of the collection\n * @param collectionName Optional name for error message\n * @throws RangeError if range is invalid\n */\nexport function checkRangeBounds(\n start: number,\n end: number,\n size: number,\n collectionName: string = \"Collection\"\n): void {\n if (start < 0 || end > size || start > end) {\n throw new RangeError(\n `${collectionName}: Invalid range [${start}, ${end}) for size ${size}`\n );\n }\n}\n\n// ============================================================================\n// Equality and search utilities\n// ============================================================================\n\n/**\n * This function finds the index of an element in an array using custom equality.\n *\n * @param array The array to search\n * @param element The element to find\n * @param eq Equality function\n * @returns Index of element, or -1 if not found\n */\nexport function findIndex<T>(array: T[], element: T, eq: Eq<T>): number {\n for (let i = 0; i < array.length; i++) {\n if (eq(array[i]!, element)) {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * This function finds the last index of an element in an array using custom equality.\n *\n * @param array The array to search\n * @param element The element to find\n * @param eq Equality function\n * @returns Last index of element, or -1 if not found\n */\nexport function findLastIndex<T>(array: T[], element: T, eq: Eq<T>): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (eq(array[i]!, element)) {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * This function gives true when an array has an element, with a custom equality.\n *\n * @param array The array to search\n * @param element The element to find\n * @param eq Equality function\n * @returns true if element is found\n */\nexport function arrayContains<T>(array: T[], element: T, eq: Eq<T>): boolean {\n return findIndex(array, element, eq) !== -1;\n}\n\n/**\n * This function removes the first occurrence of an element from an array.\n *\n * @param array The array to change\n * @param element The element to remove\n * @param eq Equality function\n * @returns true if element was found and removed\n */\nexport function arrayRemove<T>(array: T[], element: T, eq: Eq<T>): boolean {\n const index = findIndex(array, element, eq);\n if (index === -1) return false;\n array.splice(index, 1);\n return true;\n}\n\n/**\n * This function removes all occurrences of an element from an array.\n *\n * @param array The array to change\n * @param element The element to remove\n * @param eq Equality function\n * @returns Number of elements removed\n */\nexport function arrayRemoveAll<T>(array: T[], element: T, eq: Eq<T>): number {\n let count = 0;\n for (let i = array.length - 1; i >= 0; i--) {\n if (eq(array[i]!, element)) {\n array.splice(i, 1);\n count++;\n }\n }\n return count;\n}\n\n// ============================================================================\n// Iterator utilities\n// ============================================================================\n\n/**\n * This function makes a simple iterator for an array.\n *\n * @param array The array to iterate\n * @returns Iterator over the array\n */\nexport function* arrayIterator<T>(array: T[]): Iterator<T> {\n yield* array;\n}\n\n/**\n * This function makes a reversed iterator for an array.\n *\n * @param array The array to iterate\n * @returns Reversed iterator over the array\n */\nexport function* reverseArrayIterator<T>(array: T[]): Iterator<T> {\n for (let i = array.length - 1; i >= 0; i--) {\n yield array[i]!;\n }\n}\n\n/**\n * This function converts an iterable to an array.\n *\n * @param iterable The iterable to convert\n * @returns Array containing all elements\n */\nexport function toArray<T>(iterable: Iterable<T>): T[] {\n return Array.from(iterable);\n}\n\n// ============================================================================\n// Validation utilities\n// ============================================================================\n\n/**\n * This function makes sure that a value is not null or undefined.\n *\n * @param value The value to check\n * @param message Error message\n * @returns The non-null value\n * @throws Error if value is null or undefined\n */\nexport function requireNonNull<T>(value: T | null | undefined, message: string = \"Value cannot be null or undefined\"): T {\n if (value === null || value === undefined) {\n throw new Error(message);\n }\n return value;\n}\n\n/**\n * This function makes sure that a collection is not empty.\n *\n * @param size Current size\n * @param collectionName Optional name for error message\n * @throws Error if collection is empty\n */\nexport function requireNonEmpty(size: number, collectionName: string = \"Collection\"): void {\n if (size === 0) {\n throw new Error(`${collectionName} is empty`);\n }\n}\n\n// ============================================================================\n// Math utilities\n// ============================================================================\n\n/**\n * This function clamps a value between min and max.\n *\n * @param value The value to clamp\n * @param min Minimum value\n * @param max Maximum value\n * @returns Clamped value\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * This function calculates hash code for a string.\n * This function uses Java's String.hashCode() algorithm.\n *\n * @param str The string to hash\n * @returns Hash code\n */\nexport function stringHashCode(str: string): number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return hash;\n}\n"],"mappings":";;;;;;;AAmRA,MAAa,0BAA0C;;;;AAKvD,MAAa,2BAA4C;;;;AAKzD,MAAa,0BAA0C;;;;AAKvD,MAAa,uBAAoC;CAC/C,aAAa;CACb,cAAc;CACd,SAAS;CACT,UAAU;CACV,QAAQ;AACV;;;;AAKA,MAAa,0BACX;;;;AAKF,MAAa,wBAAsC;CACjD,UAAU;CACV,aAAa,OAAO;AACtB;;;;AAKA,MAAa,4BAA8C;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1P3D,SAAgB,QAA0C,GAAG,QAAkC;CAC7F,OAAOA,UAAK,GAAI,MAA2B;AAC7C;;;;;;;;;;;AAYA,MAAa,iBACX,YACA,eACyC;CACzC,OAAO,cAAc;AACvB;;;;;;;;;;;;;AAsFA,MAAa,oBACX,QACA,gBACM;CACN,OAAO,IAAI,MAAM,QAAQ,EACvB,IAAI,GAAG,MAAM,UAAU;EACrB,MAAM,QAAQ,QAAQ,IAAI,GAAG,MAAM,QAAQ;EA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O;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["fold","PRESENT","Tree.of","Tree.size","Tree.isEmpty","Tree.summary","Tree.height","Tree.at","Tree.summaryOf","Tree.concat","Tree.splitAt","Tree.split","Tree.search","Tree.locate","Tree.slice","Tree.splice","Tree.insert","Tree.remove","Tree.set","Tree.append","Tree.prepend","Tree.leaves","Tree.toArray","addEach","none","some","toArray","toSet","toMap","toList","toMap"],"sources":["../src/core/policies.ts","../src/core/middleware.ts","../src/core/events.ts","../src/core/removals.ts","../src/storage/listeners.ts","../src/order/rank.ts","../src/utils/defaults.ts","../src/impl/array-list.ts","../src/impl/array-deque.ts","../src/impl/hash-map.ts","../src/impl/linked-hash-map.ts","../src/impl/tree-map.ts","../src/impl/tree-set.ts","../src/impl/linked-list.ts","../src/impl/hash-set.ts","../src/impl/priority-queue.ts","../src/impl/summary-tree.ts","../src/core/capacity.ts","../src/behaviors/bounded.ts","../src/behaviors/readonly.ts","../src/behaviors/safe.ts","../src/behaviors/composite.ts","../src/behaviors/evented.ts","../src/behaviors/synchronized.ts","../src/behaviors/lru.ts","../src/behaviors/ttl.ts","../src/async/async-queue.ts","../src/async/channels.ts","../src/async/settled.ts","../src/async/semaphore.ts","../src/fx/iter.ts","../src/fx/collectors.ts","../src/utils/factories.ts","../src/utils/helpers.ts"],"sourcesContent":["/**\n * Policy types for configurable collection behaviors.\n *\n * Policies define how collections handle edge cases like overflow,\n * underflow, and eviction. These are used by behavior decorators\n * to give flexible, composable behavior.\n */\n\n// ============================================================================\n// Overflow Policies - what to do when a bounded collection is full\n// ============================================================================\n\n/**\n * Policy for handling overflow when adding to a full bounded collection.\n *\n * - 'throw': Throw an error when trying to add to a full collection\n * - 'drop-oldest': Remove the oldest element and add the new one\n * - 'drop-newest': Ignore the new element (don't add it)\n * - 'reject': Return false/None but don't throw (graceful failure)\n * - 'grow': Automatically increase capacity (becomes unbounded)\n * - 'block': For async collections, wait until space is available\n */\nexport type OverflowPolicy =\n | \"throw\"\n | \"drop-oldest\"\n | \"drop-newest\"\n | \"reject\"\n | \"grow\"\n | \"block\";\n\n/**\n * Context information given when overflow occurs.\n */\nexport interface OverflowContext<T> {\n /** The element that triggered the overflow. */\n readonly newElement: T;\n /** Current size of the collection. */\n readonly currentSize: number;\n /** Maximum capacity of the collection. */\n readonly capacity: number;\n /** Timestamp when overflow occurred. */\n readonly timestamp: number;\n}\n\n/**\n * Callback invoked when overflow occurs.\n * This function can log, record metrics or do custom handling.\n */\nexport type OverflowHandler<T> = (context: OverflowContext<T>) => void;\n\n// ============================================================================\n// Underflow Policies - what to do when removing from an empty collection\n// ============================================================================\n\n/**\n * Policy for handling underflow when removing from an empty collection.\n *\n * - 'throw': Throw an error when trying to remove from empty collection\n * - 'return-none': Return None/undefined (graceful failure)\n * - 'return-default': Give a default value given by user\n * - 'block': For async collections, wait until an element is available\n */\nexport type UnderflowPolicy =\n | \"throw\"\n | \"return-none\"\n | \"return-default\"\n | \"block\";\n\n/**\n * Context information given when underflow occurs.\n */\nexport interface UnderflowContext {\n /** The operation that triggered the underflow. */\n readonly operation: string;\n /** Timestamp when underflow occurred. */\n readonly timestamp: number;\n}\n\n/**\n * Callback invoked when underflow occurs.\n */\nexport type UnderflowHandler = (context: UnderflowContext) => void;\n\n// ============================================================================\n// Eviction Policies - how to choose which element to remove\n// ============================================================================\n\n/**\n * Policy for choosing which element to evict from a bounded collection.\n *\n * - 'lru': Least Recently Used - evict element not accessed for longest time\n * - 'lfu': Least Frequently Used - evict element accessed least often\n * - 'fifo': First In First Out - evict oldest inserted element\n * - 'lifo': Last In First Out - evict newest inserted element (stack-like)\n * - 'random': Evict a random element\n * - 'ttl': Time To Live - evict elements that have expired\n * - 'priority': Evict element with lowest priority\n * - 'custom': User-provided eviction function\n */\nexport type EvictionPolicy =\n | \"lru\"\n | \"lfu\"\n | \"fifo\"\n | \"lifo\"\n | \"random\"\n | \"ttl\"\n | \"priority\"\n | \"custom\";\n\n/**\n * Metadata tracked for eviction decisions.\n */\nexport interface EvictionMetadata {\n /** When the element was inserted. */\n readonly insertedAt: number;\n /** When the element was last accessed. */\n lastAccessedAt: number;\n /** How many times the element has been accessed. */\n accessCount: number;\n /** Time-to-live expiration timestamp (if applicable). */\n readonly expiresAt?: number;\n /** Priority value (higher = more important, if applicable). */\n readonly priority?: number;\n}\n\n/**\n * Information about an element that can be evicted.\n */\nexport interface EvictionCandidate<T> {\n /** The element value. */\n readonly element: T;\n /** Eviction metadata for this element. */\n readonly metadata: EvictionMetadata;\n}\n\n/**\n * Custom eviction function.\n * Given candidates, gives the element to evict.\n */\nexport type EvictionSelector<T> = (\n candidates: EvictionCandidate<T>[]\n) => T | undefined;\n\n// ============================================================================\n// Retry Policies - for async operations\n// ============================================================================\n\n/**\n * Policy for retrying failed async operations.\n */\nexport interface RetryPolicy {\n /** Maximum number of retry tries. */\n readonly maxAttempts: number;\n /** Initial delay in milliseconds. */\n readonly initialDelay: number;\n /** Backoff strategy. */\n readonly backoff: \"none\" | \"linear\" | \"exponential\";\n /** Maximum delay cap (for backoff). */\n readonly maxDelay?: number;\n /** Jitter to add randomness and avoid thundering herd. */\n readonly jitter?: boolean;\n}\n\n/**\n * Context for retry decisions.\n */\nexport interface RetryContext {\n /** Current try number (1-indexed). */\n readonly attempt: number;\n /** The error that caused the retry. */\n readonly error: unknown;\n /** Elapsed time since first try. */\n readonly elapsedMs: number;\n}\n\n/**\n * Callback to determine if an error is retryable.\n */\nexport type RetryPredicate = (context: RetryContext) => boolean;\n\n// ============================================================================\n// Conflict Resolution Policies - for concurrent modifications\n// ============================================================================\n\n/**\n * Policy for resolving conflicts when same key is changed concurrently.\n *\n * - 'last-write-wins': Most recent write takes precedence\n * - 'first-write-wins': First write takes precedence\n * - 'merge': Call merge function to combine values\n * - 'throw': Throw an error on conflict\n */\nexport type ConflictResolutionPolicy =\n | \"last-write-wins\"\n | \"first-write-wins\"\n | \"merge\"\n | \"throw\";\n\n/**\n * Function to merge conflicting values.\n */\nexport type MergeFunction<T> = (current: T, incoming: T) => T;\n\n// ============================================================================\n// Compaction Policies - for memory management\n// ============================================================================\n\n/**\n * Policy for when to compact internal storage.\n */\nexport interface CompactionPolicy {\n /** The collection compacts when the used part of its capacity is less than this ratio, from 0 to 1. */\n readonly minLoadFactor?: number;\n /** The collection compacts when its wasted space is more than this number of elements. */\n readonly maxWastedSpace?: number;\n /** When it is true, the collection compacts at each removal. */\n readonly autoCompact?: boolean;\n}\n\n// ============================================================================\n// Growth Policies - for dynamic capacity\n// ============================================================================\n\n/**\n * Policy for how to grow capacity when needed.\n */\nexport interface GrowthPolicy {\n /** Growth strategy. */\n readonly strategy: \"double\" | \"linear\" | \"golden-ratio\" | \"custom\";\n /** For linear growth, how many elements to add. */\n readonly linearIncrement?: number;\n /** For custom growth, a function to calculate new capacity. */\n readonly customGrowth?: (currentCapacity: number) => number;\n /** Maximum capacity limit (prevent unbounded growth). */\n readonly maxCapacity?: number;\n}\n\n// ============================================================================\n// Validation Policies - for type checking\n// ============================================================================\n\n/**\n * Validation action when an invalid element is encountered.\n *\n * - 'throw': Throw an error\n * - 'drop': Silently drop the invalid element\n * - 'coerce': Try to coerce to valid type\n * - 'log': Log a warning and continue\n */\nexport type ValidationPolicy = \"throw\" | \"drop\" | \"coerce\" | \"log\";\n\n/**\n * Context for validation failures.\n */\nexport interface ValidationContext<T> {\n /** The invalid element. */\n readonly element: T;\n /** Validation error message/details. */\n readonly error: unknown;\n /** The operation that triggered validation. */\n readonly operation: string;\n}\n\n/**\n * Callback invoked on validation failures.\n */\nexport type ValidationHandler<T> = (context: ValidationContext<T>) => void;\n\n// ============================================================================\n// Default policies\n// ============================================================================\n\n/**\n * Default overflow policy: throw an error.\n */\nexport const DEFAULT_OVERFLOW_POLICY: OverflowPolicy = \"throw\";\n\n/**\n * Default underflow policy: throw an error.\n */\nexport const DEFAULT_UNDERFLOW_POLICY: UnderflowPolicy = \"throw\";\n\n/**\n * Default eviction policy: FIFO (oldest first).\n */\nexport const DEFAULT_EVICTION_POLICY: EvictionPolicy = \"fifo\";\n\n/**\n * Default retry policy: 3 tries with exponential backoff.\n */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n initialDelay: 100,\n backoff: \"exponential\",\n maxDelay: 5000,\n jitter: true,\n};\n\n/**\n * Default conflict resolution: last write wins.\n */\nexport const DEFAULT_CONFLICT_POLICY: ConflictResolutionPolicy =\n \"last-write-wins\";\n\n/**\n * Default growth policy: double capacity.\n */\nexport const DEFAULT_GROWTH_POLICY: GrowthPolicy = {\n strategy: \"double\",\n maxCapacity: Number.MAX_SAFE_INTEGER,\n};\n\n/**\n * Default validation policy: throw on invalid.\n */\nexport const DEFAULT_VALIDATION_POLICY: ValidationPolicy = \"throw\";\n","/**\n * Middleware composition system for collections.\n *\n * This module gives the core composition mechanism. With it, behaviors go in layers\n * on top of collections with the decorator pattern.\n *\n * The mechanism is for synchronous collection operations. The collection instance itself\n * is the context, so a behavior needs no explicit context object.\n *\n * @example\n * const list = compose(\n * safeList<number>(),\n * eventedList<number>(),\n * boundedList<number>({ capacity: 100 })\n * )(arrayList<number>())\n */\n\nimport type { Collection } from \"../interfaces/collection.js\";\nimport { compose as fold, type Chain, type Layer, type Stacked } from \"./layers.js\";\n\n/**\n * A middleware is a function that takes a collection and gives\n * an enhanced version of that collection.\n *\n * This maps to the unified middleware pattern where:\n * - The \"context\" is the collection itself (passed directly, not in a context object)\n * - Execution is synchronous (no Promises)\n * - Type transformation is tracked through In -> Out\n *\n * Middleware can:\n * - Intercept method calls\n * - Add new capabilities\n * - Transform inputs/outputs\n * - Delegate to the next layer\n *\n * @template In The input collection type\n * @template Out The output collection type (defaults to In if not specified)\n */\nexport type Middleware<In = any, Out extends In = In> = (next: In) => Out;\n\n/**\n * Composes multiple middleware layers into a single enhancer function.\n *\n * This function uses reduceRight to make an \"onion\" pattern where the first middleware\n * is the outermost layer (runs first when calling into the collection).\n *\n * The type system properly tracks capability additions through composition.\n *\n * @example\n * // Layer order (outer to inner):\n * // 1. safe - converts throws to Option/Result\n * // 2. evented - emits events on mutations\n * // 3. bounded - enforces capacity limits\n * // 4. base - the underlying ArrayList\n * const enhancer = compose(\n * safeList<number>(),\n * eventedList<number>(),\n * boundedList<number>({ capacity: 100 })\n * )\n * const list = enhancer(arrayList<number>())\n * // Type: List<number> & SafeCollection & EventedCollection & BoundedCollection\n *\n * @param layers The middleware layers to compose\n * @returns A function that applies all layers to a base collection\n */\nexport function compose<const L extends readonly Layer[]>(...layers: L & Chain<L>): Stacked<L> {\n return fold(...(layers as readonly Layer[])) as unknown as Stacked<L>;\n}\n\n/**\n * Utility to check if a collection has a specific capability.\n * Useful for middleware that wants to conditionally enhance behavior.\n *\n * @example\n * if (hasCapability(collection, 'on')) {\n * // Collection supports events\n * collection.on('add', handler)\n * }\n */\nexport const hasCapability = <C extends Collection<any>, K extends keyof any>(\n collection: C,\n capability: K\n): collection is C & Record<K, unknown> => {\n return capability in collection;\n};\n\n/**\n * Marker interface for collections that support events.\n * Middleware can use this to detect event capability.\n */\nexport interface Evented<E extends Record<string, any>> {\n /**\n * This method subscribes a listener to an event.\n * @returns Unsubscribe function\n */\n on<K extends keyof E>(event: K, handler: (payload: E[K]) => void): () => void;\n\n /**\n * This method emits an event. Only the middleware calls it.\n * @internal\n */\n emit?<K extends keyof E>(event: K, payload: E[K]): void;\n}\n\n/**\n * Marker interface for collections that support async operations.\n */\nexport interface Async<T> {\n /**\n * Async iterator for consuming elements.\n */\n [Symbol.asyncIterator](): AsyncIterator<T>;\n}\n\n/**\n * Marker interface for collections that are bounded.\n */\nexport interface BoundedCollection {\n /** Maximum capacity */\n readonly capacity: number;\n /** If collection is at capacity */\n readonly isFull: boolean;\n /** Remaining space */\n readonly remainingCapacity: number;\n}\n\n/**\n * Marker interface for collections that support safe (Option/Result) operations.\n */\nexport interface SafeCollection {\n /**\n * Namespace for safe operations that return Option/Result instead of throwing.\n */\n readonly safe: unknown;\n}\n\n/**\n * This type gives the element type of a collection.\n */\nexport type ElementType<C> = C extends {\n [Symbol.iterator](): Iterator<infer T>;\n}\n ? T\n : C extends { get(index: number): infer T }\n ? T\n : C extends { peek(): infer T }\n ? T\n : never;\n\n/**\n * This type changes each method of a type so that it gives its async equivalent.\n */\nexport type Asyncify<C> = {\n [K in keyof C]: C[K] extends (...args: infer Args) => infer R\n ? (...args: Args) => Promise<R>\n : C[K];\n};\n\n/**\n * Helper to make a proxy that intercepts method calls.\n * Useful for implementing middleware that needs to wrap method invocations.\n *\n * @example\n * const logged = interceptMethods(collection, (target, method, args) => {\n * console.log(`Calling ${String(method)} with`, args)\n * const result = Reflect.apply(target[method], target, args)\n * console.log(`Result:`, result)\n * return result\n * })\n */\nexport const interceptMethods = <C extends object>(\n target: C,\n interceptor: (target: C, method: keyof C, args: unknown[]) => unknown\n): C => {\n return new Proxy(target, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver);\n if (typeof value === \"function\" && typeof prop === \"string\") {\n return function (this: unknown, ...args: unknown[]) {\n return interceptor(t, prop as keyof C, args);\n };\n }\n return value;\n },\n });\n};\n\n/**\n * Helper to make a readonly view of a collection by blocking mutating methods.\n *\n * @param mutatingMethods Set of method names that the middleware blocks\n * @param errorMessage Custom error message to throw\n */\nexport const blockMethods = <C extends object>(\n target: C,\n mutatingMethods: Set<string | symbol>,\n errorMessage: string = \"Operation not allowed\"\n): C => {\n return new Proxy(target, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver);\n if (typeof value === \"function\" && mutatingMethods.has(prop)) {\n return () => {\n throw new Error(errorMessage);\n };\n }\n return value;\n },\n });\n};\n\n/**\n * Helper to delegate method calls to a target while maintaining correct context.\n * Useful when wrapping collections.\n */\nexport const delegate = <C extends object, T extends C>(\n target: T,\n wrapper: Partial<C>\n): C => {\n return new Proxy(target, {\n get(t, prop, receiver) {\n // If wrapper has the property, use it\n if (prop in wrapper) {\n return Reflect.get(wrapper, prop, receiver);\n }\n // Otherwise delegate to target\n const value = Reflect.get(t, prop, receiver);\n // Bind methods to maintain correct 'this' context\n if (typeof value === \"function\") {\n return value.bind(t);\n }\n return value;\n },\n }) as C;\n};\n\n/**\n * Utility type to add optional capabilities to a collection type.\n */\nexport type WithCapability<C, Cap> = C & Cap;\n\n/**\n * Builder pattern helper for fluent API construction.\n *\n * @example\n * class ListBuilder<T> {\n * private middleware: Middleware<List<T>>[] = []\n *\n * bounded(capacity: number) {\n * this.middleware.push(boundedList({ capacity }))\n * return this\n * }\n *\n * evented() {\n * this.middleware.push(eventedList())\n * return this\n * }\n *\n * build(): List<T> {\n * return compose(...this.middleware)(arrayList<T>())\n * }\n * }\n */\nexport abstract class CollectionBuilder<C> {\n protected middleware: Middleware<C>[] = [];\n\n /**\n * This method applies a custom middleware.\n */\n use(middleware: Middleware<C>): this {\n this.middleware.push(middleware);\n return this;\n }\n\n /**\n * This method builds the final collection: it composes all middleware with the base.\n */\n abstract build(): C;\n}\n\n/**\n * Utility to make a middleware that only enhances specific methods.\n *\n * @example\n * const logAdd = enhanceMethod('add', (original, args) => {\n * console.log('Adding:', args[0])\n * return original(...args)\n * })\n */\nexport const enhanceMethod = <C extends object, K extends keyof C & string>(\n methodName: K,\n enhancer: (\n original: C[K] extends (...args: infer Args) => infer R\n ? (...args: Args) => R\n : never,\n args: C[K] extends (...args: infer Args) => any ? Args : never\n ) => C[K] extends (...args: any[]) => infer R ? R : never\n): Middleware<C> => {\n return (next: C): C => {\n type MethodArgs = C[K] extends (...args: infer Args) => any ? Args : never;\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === methodName && typeof value === \"function\") {\n return function (this: unknown, ...args: unknown[]) {\n return enhancer(value.bind(target), args as MethodArgs);\n };\n }\n return value;\n },\n });\n };\n};\n\n/**\n * This function combines multiple middleware into a single middleware.\n * Useful for making reusable middleware bundles.\n *\n * Bundle has the same composition semantics as compose - the first middleware\n * is the outermost layer, and types are tracked through the chain.\n *\n * @example\n * const standardBehaviors = bundle(\n * boundedList<number>({ capacity: 1000 }),\n * eventedList<number>(),\n * safeList<number>()\n * )\n *\n * const list = compose(standardBehaviors)(arrayList<number>())\n */\nexport const bundle: typeof compose = compose;\n","/**\n * Typed event emitter system for collections.\n *\n * This function gives a lightweight, type-safe event system for mutation events\n * and other observable behavior. Events are strongly typed using\n * TypeScript's mapped types.\n */\n\n/**\n * A listener function that receives an event payload.\n */\nexport type Listener<P> = (payload: P) => void;\n\n/**\n * A function to unsubscribe from an event.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Event map defining event names and their payload types.\n *\n * @example\n * interface MyEvents {\n * add: { value: number; index: number }\n * remove: { value: number }\n * clear: {}\n * }\n */\nexport type EventMap = Record<string, any>;\n\n/**\n * Type-safe event emitter.\n *\n * This class supports subscribing to events, emitting events, and managing listeners.\n * All event names and payloads are type-checked at compile time.\n *\n * @example\n * interface ListEvents<T> {\n * add: { value: T; index: number }\n * remove: { value: T; index: number }\n * clear: {}\n * }\n *\n * const emitter = new Emitter<ListEvents<number>>()\n *\n * const unsub = emitter.on('add', ({ value, index }) => {\n * console.log(`Added ${value} at ${index}`)\n * })\n *\n * emitter.emit('add', { value: 42, index: 0 })\n * unsub() // Unsubscribe\n */\nexport class Emitter<E extends EventMap> {\n private listeners = new Map<keyof E, Set<Listener<any>>>();\n\n /**\n * This method subscribes a listener to an event.\n *\n * @param event The event name\n * @param listener The callback to invoke when event is emitted\n * @returns A function to unsubscribe\n */\n on<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n listeners = new Set();\n this.listeners.set(event, listeners);\n }\n listeners.add(listener);\n\n // Return unsubscribe function\n return () => {\n listeners!.delete(listener);\n // An off() can replace the set of the event. Remove only the set of this subscription.\n if (listeners!.size === 0 && this.listeners.get(event) === listeners) {\n this.listeners.delete(event);\n }\n };\n }\n\n /**\n * This method subscribes a listener to an event, and unsubscribes it after the first emission.\n *\n * @param event The event name\n * @param listener The callback to invoke once\n * @returns A function to unsubscribe (in case you want to cancel before emission)\n */\n once<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {\n const wrappedListener: Listener<E[K]> = (payload) => {\n unsubscribe();\n listener(payload);\n };\n\n const unsubscribe = this.on(event, wrappedListener);\n return unsubscribe;\n }\n\n /**\n * This method emits an event to all registered listeners.\n *\n * @param event The event name\n * @param payload The event payload\n */\n emit<K extends keyof E>(event: K, payload: E[K]): void {\n const listeners = this.listeners.get(event);\n if (listeners) {\n // Create a snapshot to avoid issues if listeners modify the set\n const snapshot = Array.from(listeners);\n for (const listener of snapshot) {\n try {\n listener(payload);\n } catch (error) {\n // Log error but don't stop other listeners\n console.error(\n `Error in event listener for '${String(event)}':`,\n error\n );\n }\n }\n }\n }\n\n /**\n * This method removes all listeners of an event, or of all events when the call gives no event.\n *\n * @param event Optional event name to clear listeners for\n */\n off<K extends keyof E>(event?: K): void {\n if (event !== undefined) {\n this.listeners.delete(event);\n } else {\n this.listeners.clear();\n }\n }\n\n /**\n * This method gives the number of listeners of an event.\n *\n * @param event The event name\n * @returns Number of registered listeners\n */\n listenerCount<K extends keyof E>(event: K): number {\n return this.listeners.get(event)?.size ?? 0;\n }\n\n /**\n * This method gives the names of the events that have one or more listeners.\n */\n eventNames(): (keyof E)[] {\n return Array.from(this.listeners.keys());\n }\n\n /**\n * This method gives true when an event has one or more listeners.\n */\n hasListeners<K extends keyof E>(event: K): boolean {\n return this.listenerCount(event) > 0;\n }\n\n /**\n * This method removes all listeners and releases the resources.\n */\n dispose(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * This function makes an event emitter for an event map.\n *\n * This is a convenience factory function.\n *\n * @example\n * const events = createEmitter<ListEvents<number>>()\n */\nexport const createEmitter = <E extends EventMap>(): Emitter<E> => {\n return new Emitter<E>();\n};\n\n/**\n * Event batching utility for reducing event noise.\n * This class collects events and emits them in batches.\n *\n * @example\n * const batcher = new EventBatcher(emitter, 'add', 100)\n * batcher.queue({ value: 1, index: 0 })\n * batcher.queue({ value: 2, index: 1 })\n * // After 100ms or flush(), emits single 'batch-add' event with both items\n */\nexport class EventBatcher<E extends EventMap, K extends keyof E> {\n private emitter: Emitter<E & { [P in `batch-${K & string}`]: E[K][] }>;\n private event: K;\n private delayMs: number;\n private batch: E[K][] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n emitter: Emitter<E & { [P in `batch-${K & string}`]: E[K][] }>,\n event: K,\n delayMs: number\n ) {\n this.emitter = emitter;\n this.event = event;\n this.delayMs = delayMs;\n }\n\n /**\n * This method adds an event to the current batch.\n */\n queue(payload: E[K]): void {\n this.batch.push(payload);\n\n if (this.timer === null) {\n this.timer = setTimeout(() => this.flush(), this.delayMs);\n }\n }\n\n /**\n * This method emits all batched events at once.\n */\n flush(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n if (this.batch.length > 0) {\n const batchEvent = `batch-${String(this.event)}` as keyof (E & { [P in `batch-${K & string}`]: E[K][] });\n this.emitter.emit(batchEvent, this.batch as any);\n this.batch = [];\n }\n }\n\n /**\n * This method sends the events of the batch and releases the resources.\n */\n dispose(): void {\n this.flush();\n }\n}\n\n/**\n * Async event emitter that gives promises.\n * This class waits for all async listeners to complete.\n *\n * @example\n * const emitter = new AsyncEmitter<{ save: { data: string } }>()\n *\n * emitter.on('save', async ({ data }) => {\n * await database.save(data)\n * })\n *\n * await emitter.emit('save', { data: 'test' }) // Waits for save\n */\nexport class AsyncEmitter<E extends EventMap> {\n private listeners = new Map<keyof E, Set<Listener<any>>>();\n\n on<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n listeners = new Set();\n this.listeners.set(event, listeners);\n }\n listeners.add(listener);\n\n return () => {\n listeners!.delete(listener);\n // An off() can replace the set of the event. Remove only the set of this subscription.\n if (listeners!.size === 0 && this.listeners.get(event) === listeners) {\n this.listeners.delete(event);\n }\n };\n }\n\n /**\n * This method emits an event and waits until all async listeners complete.\n *\n * @param event The event name\n * @param payload The event payload\n * @returns Promise that resolves when all listeners complete\n */\n async emit<K extends keyof E>(event: K, payload: E[K]): Promise<void> {\n const listeners = this.listeners.get(event);\n if (listeners) {\n const promises = Array.from(listeners).map((listener) =>\n Promise.resolve().then(() => listener(payload))\n );\n await Promise.all(promises);\n }\n }\n\n off<K extends keyof E>(event?: K): void {\n if (event !== undefined) {\n this.listeners.delete(event);\n } else {\n this.listeners.clear();\n }\n }\n\n listenerCount<K extends keyof E>(event: K): number {\n return this.listeners.get(event)?.size ?? 0;\n }\n\n eventNames(): (keyof E)[] {\n return Array.from(this.listeners.keys());\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * Utility to forward events from one emitter to another.\n * Useful for composing event sources.\n *\n * @example\n * const child = new Emitter<ChildEvents>()\n * const parent = new Emitter<ParentEvents>()\n *\n * forwardEvent(child, parent, 'childEvent', 'parentEvent')\n */\nexport const forwardEvent = <\n E1 extends EventMap,\n E2 extends EventMap,\n K1 extends keyof E1,\n K2 extends keyof E2\n>(\n source: Emitter<E1>,\n target: Emitter<E2>,\n sourceEvent: K1,\n targetEvent: K2,\n transform?: (payload: E1[K1]) => E2[K2]\n): Unsubscribe => {\n return source.on(sourceEvent, (payload) => {\n const transformedPayload = transform\n ? transform(payload)\n : (payload as any);\n target.emit(targetEvent, transformedPayload);\n });\n};\n\n/**\n * This function makes a filtered event subscription that fires only when the predicate is true.\n *\n * @example\n * const emitter = new Emitter<{ change: { value: number } }>()\n *\n * onWhen(emitter, 'change', ({ value }) => value > 10, ({ value }) => {\n * console.log('Value exceeded 10:', value)\n * })\n */\nexport const onWhen = <E extends EventMap, K extends keyof E>(\n emitter: Emitter<E>,\n event: K,\n predicate: (payload: E[K]) => boolean,\n listener: Listener<E[K]>\n): Unsubscribe => {\n return emitter.on(event, (payload) => {\n if (predicate(payload)) {\n listener(payload);\n }\n });\n};\n","/**\n * The removal channel of a stack of layers (C23).\n *\n * Some layers remove entries or elements by themselves. The bounded layers drop one when they are full.\n * `lruMap` evicts one, and `ttlMap` removes an expired one. A layer\n * above them does not call these removals, so it cannot see them. The removal channel tells it.\n *\n * - Each removing layer gives its channel under the key `removals`. Its channel gives its own removals and the\n * removals of the channel below it.\n * - A layer that does not remove forwards the channel below it: a proxy gives each unknown key of its target.\n * - `eventedMap` and the other evented layers emit an event for each removal of the channel below them.\n *\n * @example\n * const cache = compose(eventedMap<string, number>(), lruMap({ capacity: 2 }))(hashMap());\n * cache.on(\"delete\", ({ key, reason }) => console.log(key, reason)); // an eviction gives the reason \"evict\"\n */\n\nimport type { Listener, Unsubscribe } from \"./events.js\";\n\n/** The key of the removal channel on a layer. */\nexport const removals: unique symbol = Symbol.for(\"@mark1russell7/collections/removals\");\n\n/**\n * The cause of a removal: a bounded layer drops, `lruMap` evicts and `ttlMap` removes an expired entry.\n */\nexport type RemovalReason = \"drop\" | \"evict\" | \"expire\";\n\n/** A removal from a map: the key and the value that the layer removed. */\nexport interface MapRemoval<K, V> {\n readonly key: K;\n readonly value: V;\n readonly reason: RemovalReason;\n}\n\n/**\n * A removal of an element: the element and the end that it left. A removal from a collection with no ends,\n * for example by `ttlCollection`, has no `end`.\n */\nexport interface ElementRemoval<T> {\n readonly value: T;\n readonly end?: \"first\" | \"last\";\n readonly reason: RemovalReason;\n}\n\n/** A channel of removals. The listener gets each removal after the collection changed. */\nexport interface RemovalChannel<R> {\n on(listener: Listener<R>): Unsubscribe;\n}\n\n/** The channel of a removing layer, and the function that sends its own removals. */\nexport interface RemovalSource<R> {\n readonly channel: RemovalChannel<R>;\n emit(removal: R): void;\n}\n\n/**\n * This function gives the removal channel of a collection, or `undefined` when no layer of it removes.\n */\nexport function removalsOf<R>(collection: object): RemovalChannel<R> | undefined {\n const channel: unknown = (collection as { readonly [removals]?: unknown })[removals];\n if (typeof channel !== \"object\" || channel === null) return undefined;\n return typeof (channel as { on?: unknown }).on === \"function\" ? (channel as RemovalChannel<R>) : undefined;\n}\n\n/**\n * This function makes the channel of a removing layer over `next`.\n * The channel forwards each removal below. It calls `below` first, so the layer corrects its own state first.\n */\nexport function removalSource<R>(next: object, below?: (removal: R) => void): RemovalSource<R> {\n const listeners = new Set<Listener<R>>();\n const emit = (removal: R): void => {\n for (const listener of [...listeners]) listener(removal);\n };\n removalsOf<R>(next)?.on((removal) => {\n below?.(removal);\n emit(removal);\n });\n const channel: RemovalChannel<R> = {\n on(listener) {\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n };\n return { channel, emit };\n}\n","/**\n * A set of listeners for the events of a storage: the change batches of `observe()`, or the status\n * of a sync. A storage package uses it, so each storage treats its listeners in the same way.\n */\n\n/** The function that gets the error of a listener. */\nexport type ListenerErrorHandler = (error: unknown) => void;\n\n/**\n * The default handler of the error of a listener. It throws the error again in a microtask, as an\n * `EventTarget` reports the error of a listener. Thus the error is not lost, and the write that\n * sent the event does not fail.\n */\nexport const reportListenerError: ListenerErrorHandler = (error) => {\n queueMicrotask(() => {\n throw error;\n });\n};\n\n/**\n * The listeners of one kind of event.\n *\n * - `emit()` gives the event to each listener, in the order of `add()`.\n * - A listener that `add()` gets during an `emit()` gets the next event, not this one.\n * - The error of a listener goes to the error handler. The other listeners get the event.\n * - The same function can be added two times. Each `add()` gives its own function that removes it.\n */\nexport class StorageListeners<E> {\n private readonly listeners = new Set<{ readonly listener: (event: E) => void }>();\n private readonly onError: ListenerErrorHandler;\n\n /** @param onError - The function that gets the error of a listener. The default is `reportListenerError`. */\n constructor(onError: ListenerErrorHandler = reportListenerError) {\n this.onError = onError;\n }\n\n /** The number of listeners. */\n get size(): number {\n return this.listeners.size;\n }\n\n /**\n * This method adds a listener.\n *\n * @returns The function that removes the listener. A second use of it does nothing.\n */\n add(listener: (event: E) => void): () => void {\n const entry = { listener };\n this.listeners.add(entry);\n return () => {\n this.listeners.delete(entry);\n };\n }\n\n /** This method gives the event to each listener. */\n emit(event: E): void {\n for (const entry of [...this.listeners]) {\n // A listener that a listener before it removed gets no event\n if (!this.listeners.has(entry)) continue;\n try {\n entry.listener(event);\n } catch (error) {\n this.onError(error);\n }\n }\n }\n\n /** This method removes each listener. */\n clear(): void {\n this.listeners.clear();\n }\n}\n","/**\n * The keys of an ordered list: fractional indexing with base-62 keys. A\n * key is a string. Each item of the list keeps one, and the list sorts by it. An item that moves\n * between two others gets a key between theirs, so a move writes one item and no other.\n *\n * - A key has an integer part and a fraction part. The first character of the integer part gives its\n * length. An insertion at an end changes the integer part, so the keys stay short.\n * - An insertion between two keys uses the fraction part, which can grow without a limit. Thus the keys\n * do not run out, and the list needs no rebalance.\n * - Compare two keys by the code units of the strings (`a < b`), not with `localeCompare`.\n * - Two writers that move items into the same gap at the same time can get the same key. Sort by the\n * key, then by the id of the item, so each reader sees one order.\n *\n * The algorithm is the one of the `fractional-indexing` package of Rocicorp (CC0), after the article\n * \"Implementing Fractional Indexing\" of David Greenspan.\n */\n\n/** The digits of a key, in ascending order of their code units. */\nexport const KEY_DIGITS = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nconst ZERO = KEY_DIGITS[0]!;\nconst LAST = KEY_DIGITS[KEY_DIGITS.length - 1]!;\n/** The smallest integer part. No key comes before it. */\nconst SMALLEST_INTEGER = `A${ZERO.repeat(26)}`;\n\nfunction invalid(message: string): RangeError {\n return new RangeError(message);\n}\n\n/** This function gives the length of an integer part from its head character: a to z and Z to A give 2 to 27. */\nfunction integerLength(head: string): number {\n if (head >= \"a\" && head <= \"z\") return head.charCodeAt(0) - \"a\".charCodeAt(0) + 2;\n if (head >= \"A\" && head <= \"Z\") return \"Z\".charCodeAt(0) - head.charCodeAt(0) + 2;\n throw invalid(`A key cannot start with \"${head}\"`);\n}\n\nfunction integerPart(key: string): string {\n const length = integerLength(key[0] ?? \"\");\n if (length > key.length) throw invalid(`The key \"${key}\" is too short for its integer part`);\n return key.slice(0, length);\n}\n\nfunction validateKey(key: string): void {\n if (typeof key !== \"string\" || key === \"\") throw invalid(\"A key is a string that is not empty\");\n for (const c of key) if (!KEY_DIGITS.includes(c)) throw invalid(`The key \"${key}\" has a character that is no digit of a key`);\n if (key === SMALLEST_INTEGER) throw invalid(`The key \"${key}\" is reserved`);\n const fraction = key.slice(integerPart(key).length);\n if (fraction.endsWith(ZERO)) throw invalid(`The fraction part of the key \"${key}\" ends with ${ZERO}`);\n}\n\n/** A fraction strictly between two fractions. `b` null is the end. Neither one ends with the zero digit. */\nfunction midpoint(a: string, b: string | null): string {\n if (b !== null) {\n let n = 0;\n while ((a[n] ?? ZERO) === b[n]) n++;\n if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));\n }\n const digitA = a ? KEY_DIGITS.indexOf(a[0]!) : 0;\n const digitB = b !== null ? KEY_DIGITS.indexOf(b[0]!) : KEY_DIGITS.length;\n if (digitB - digitA > 1) return KEY_DIGITS[Math.round((digitA + digitB) / 2)]!;\n // The first digits are next to each other\n if (b !== null && b.length > 1) return b.slice(0, 1);\n return KEY_DIGITS[digitA]! + midpoint(a.slice(1), null);\n}\n\nfunction incrementInteger(x: string): string | null {\n const [head, ...digits] = x.split(\"\") as [string, ...string[]];\n let carry = true;\n for (let i = digits.length - 1; carry && i >= 0; i--) {\n const d = KEY_DIGITS.indexOf(digits[i]!) + 1;\n if (d === KEY_DIGITS.length) digits[i] = ZERO;\n else {\n digits[i] = KEY_DIGITS[d]!;\n carry = false;\n }\n }\n if (!carry) return head + digits.join(\"\");\n if (head === \"Z\") return `a${ZERO}`;\n if (head === \"z\") return null;\n const next = String.fromCharCode(head.charCodeAt(0) + 1);\n if (next > \"a\") digits.push(ZERO);\n else digits.pop();\n return next + digits.join(\"\");\n}\n\nfunction decrementInteger(x: string): string | null {\n const [head, ...digits] = x.split(\"\") as [string, ...string[]];\n let borrow = true;\n for (let i = digits.length - 1; borrow && i >= 0; i--) {\n const d = KEY_DIGITS.indexOf(digits[i]!) - 1;\n if (d === -1) digits[i] = LAST;\n else {\n digits[i] = KEY_DIGITS[d]!;\n borrow = false;\n }\n }\n if (!borrow) return head + digits.join(\"\");\n if (head === \"a\") return `Z${LAST}`;\n if (head === \"A\") return null;\n const next = String.fromCharCode(head.charCodeAt(0) - 1);\n if (next < \"Z\") digits.push(LAST);\n else digits.pop();\n return next + digits.join(\"\");\n}\n\n/**\n * This function gives a key strictly between two keys. Without `prev`, the key comes before `next`.\n * Without `next`, it comes after `prev`. Without both, it gives the first key of a list (\"a0\").\n *\n * @throws RangeError when a key is not valid, or when `prev` is not before `next`\n *\n * @example\n * ```ts\n * keyBetween(undefined, undefined); // \"a0\"\n * keyBetween(\"a0\", undefined); // \"a1\", after a0\n * keyBetween(\"a0\", \"a1\"); // \"a0V\"\n * ```\n */\nexport function keyBetween(prev: string | null | undefined, next: string | null | undefined): string {\n const a = prev ?? null;\n const b = next ?? null;\n if (a !== null) validateKey(a);\n if (b !== null) validateKey(b);\n if (a !== null && b !== null && a >= b) throw invalid(`The key \"${a}\" is not before the key \"${b}\"`);\n if (a === null) {\n if (b === null) return `a${ZERO}`;\n const ib = integerPart(b);\n const fb = b.slice(ib.length);\n if (ib === SMALLEST_INTEGER) return ib + midpoint(\"\", fb);\n if (ib < b) return ib;\n const decremented = decrementInteger(ib);\n if (decremented === null) throw invalid(\"No key comes before this one\");\n return decremented;\n }\n const ia = integerPart(a);\n const fa = a.slice(ia.length);\n if (b === null) {\n const incremented = incrementInteger(ia);\n return incremented === null ? ia + midpoint(fa, null) : incremented;\n }\n const ib = integerPart(b);\n const fb = b.slice(ib.length);\n if (ia === ib) return ia + midpoint(fa, fb);\n const incremented = incrementInteger(ia);\n if (incremented === null) throw invalid(\"No key comes after this one\");\n if (incremented < b) return incremented;\n return ia + midpoint(fa, null);\n}\n\n/**\n * This function gives `count` keys in ascending order, strictly between two keys.\n * Use it to put several items at one place, or to give keys to a new list.\n *\n * @throws RangeError as `keyBetween`, or when `count` is not an integer of 0 or more\n */\nexport function keysBetween(prev: string | null | undefined, next: string | null | undefined, count: number): string[] {\n if (!Number.isInteger(count) || count < 0) throw invalid(`A count of keys is an integer of 0 or more, not ${count}`);\n const a = prev ?? null;\n const b = next ?? null;\n if (count === 0) return [];\n if (count === 1) return [keyBetween(a, b)];\n if (b === null) {\n const keys = [keyBetween(a, null)];\n for (let i = 1; i < count; i++) keys.push(keyBetween(keys[i - 1]!, null));\n return keys;\n }\n if (a === null) {\n const keys = [keyBetween(null, b)];\n for (let i = 1; i < count; i++) keys.push(keyBetween(null, keys[i - 1]!));\n return keys.reverse();\n }\n const half = Math.floor(count / 2);\n const middle = keyBetween(a, b);\n return [...keysBetween(a, middle, half), middle, ...keysBetween(middle, b, count - half - 1)];\n}\n\n/** The options of `isValidKey`. */\nexport interface KeyCheckOptions {\n /** The longest key that the check accepts. The default is 1024 characters. */\n readonly maxLength?: number;\n}\n\n/**\n * This function tells if a value is a valid key, for example a key that a client writes. A key that\n * is longer than `maxLength` is not valid.\n */\nexport function isValidKey(key: unknown, options: KeyCheckOptions = {}): key is string {\n if (typeof key !== \"string\" || key.length > (options.maxLength ?? 1024)) return false;\n try {\n validateKey(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/** An item of an ordered list: its id and its key. */\nexport interface KeyedItem {\n readonly id: string;\n readonly key: string;\n}\n\n/**\n * This function gives the writes of a move: the new key of the item that moves, and new keys for the\n * neighbors that need them. Give the other items of the list in order (by key, then by id), without\n * the item that moves. Also give the index of the drop, from 0 to their number (`dropIndex`).\n *\n * Two writers can give two items one key. A drop between two such items has no key between them.\n * So the helper first gives new keys to the items after the drop that have the key of the item before\n * it. Each write is `{ id, key }`. The writes of the neighbors come first, and the write of the item\n * that moves comes last.\n *\n * @throws RangeError when the index is outside the list, when the list holds the item that moves, or\n * when a key is not valid\n *\n * @example\n * ```ts\n * const index = dropIndex(pointer, others.map(centerOf));\n * for (const { id, key } of keysForDrop(others, index, dragged.id)) await save(id, { rank: key });\n * ```\n */\nexport function keysForDrop(items: readonly KeyedItem[], index: number, movingId: string): Array<{ id: string; key: string }> {\n if (!Number.isInteger(index) || index < 0 || index > items.length) throw invalid(`The index ${index} is outside the list of ${items.length} items`);\n if (items.some((item) => item.id === movingId)) throw invalid(`The list holds the item that moves (${movingId})`);\n const prev = items[index - 1]?.key ?? null;\n // The items from the index on that do not come after the item before the drop need new keys\n let end = index;\n while (end < items.length && prev !== null && items[end]!.key <= prev) end++;\n const writes: Array<{ id: string; key: string }> = [];\n if (end > index) {\n const keys = keysBetween(prev, items[end]?.key ?? null, end - index);\n for (let i = index; i < end; i++) writes.push({ id: items[i]!.id, key: keys[i - index]! });\n }\n const next = writes.length > 0 ? writes[0]!.key : (items[index]?.key ?? null);\n writes.push({ id: movingId, key: keyBetween(prev, next) });\n return writes;\n}\n\n/** The order of two keys: the code units of the strings, as the keys need (not `localeCompare`). */\nexport function compareKeys(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** A point, for example the center of an item on the screen. */\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * This function gives the index at which a point goes among the items of a list on the screen.\n * The reading order is the rows from top to bottom, and each row from left to right.\n * The index is that of the first item whose center comes after the point, from 0 to the number of items. A center within\n * `rowTolerance` of the point on the vertical axis is in the row of the point.\n *\n * Give the centers in reading order, the same order as the keys, and without the item that moves.\n *\n * @example\n * ```ts\n * const index = dropIndex(pointer, others.map(centerOf));\n * const key = keyBetween(keys[index - 1], keys[index]);\n * ```\n */\nexport function dropIndex(point: Point, centers: readonly Point[], rowTolerance = 24): number {\n for (let i = 0; i < centers.length; i++) {\n const c = centers[i]!;\n if (point.y < c.y - rowTolerance) return i;\n if (Math.abs(point.y - c.y) <= rowTolerance && point.x < c.x) return i;\n }\n return centers.length;\n}\n","/**\n * Default implementations of equality, hashing, and comparison functions.\n *\n * This module gives sensible defaults for primitive types and utilities for\n * making custom comparators.\n */\n\nimport type { Eq, Hash, Compare } from \"../core/traits.js\";\n\n// ============================================================================\n// Default Equality\n// ============================================================================\n\n/**\n * Default equality using strict equality (===).\n * Works for primitives and reference equality for objects.\n */\nexport const defaultEq: Eq<any> = (a, b) => a === b;\n\n/**\n * Structural equality for objects (shallow comparison of properties).\n * This function compares own enumerable properties using ===.\n */\nexport const shallowEq: Eq<any> = (a, b) => {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n if (a === null || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) return false;\n if (a[key] !== b[key]) return false;\n }\n\n return true;\n};\n\n/** SameValueZero: the meaning of `===`, and NaN equals NaN. */\nconst sameValueZero = (a: unknown, b: unknown): boolean => a === b || (Number.isNaN(a) && Number.isNaN(b));\n\nconst isObject = (value: unknown): value is object => typeof value === \"object\" && value !== null;\n\n/** The pairs that one comparison holds equal. The log lets a failed try remove its pairs. */\ninterface HeldPairs {\n readonly partners: Map<object, Set<object>>;\n readonly log: [object, object][];\n}\n\nfunction releasePairs(held: HeldPairs, mark: number): void {\n while (held.log.length > mark) {\n const [a, b] = held.log.pop()!;\n held.partners.get(a)?.delete(b);\n }\n}\n\nfunction equalElements(a: ArrayLike<unknown>, b: ArrayLike<unknown>): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!sameValueZero(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The kinds of `equalObjects` and `hashFields`, so that the relation and its hash stay in step. */\nconst isBinary = (value: object): value is ArrayBufferLike | DataView =>\n value instanceof DataView || value instanceof ArrayBuffer || (typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer);\n\nconst isOpaque = (value: object): boolean => value instanceof Promise || value instanceof WeakMap || value instanceof WeakSet || value instanceof WeakRef;\n\nconst isBoxed = (value: object): boolean =>\n value instanceof Number || value instanceof String || value instanceof Boolean || value instanceof BigInt || value instanceof Symbol;\n\nfunction bytesOf(value: ArrayBufferLike | DataView): Uint8Array {\n return ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value);\n}\n\nfunction enumerableKeys(value: object): (string | symbol)[] {\n return Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));\n}\n\nfunction equalKeys(a: any, b: any, held: HeldPairs): boolean {\n const keys = enumerableKeys(a);\n if (keys.length !== enumerableKeys(b).length) return false;\n return keys.every((key) => Object.prototype.propertyIsEnumerable.call(b, key) && equalValues(a[key], b[key], held));\n}\n\n/**\n * The comparison of the entries of two maps, or of the members of two sets. A primitive key finds\n * its partner by `has`. An object key tries each object key of `b` that is not taken yet. The first\n * partner is correct, because the relation is an equivalence.\n */\nfunction equalEntries(a: Map<unknown, unknown> | Set<unknown>, b: Map<unknown, unknown> | Set<unknown>, held: HeldPairs): boolean {\n if (a.size !== b.size) return false;\n const valueAt = (key: unknown): unknown => (b instanceof Map ? b.get(key) : key);\n const free = [...b.entries()].filter(([key]) => isObject(key));\n for (const [key, value] of a.entries()) {\n if (!isObject(key)) {\n if (!b.has(key) || !equalValues(value, valueAt(key), held)) return false;\n continue;\n }\n const at = free.findIndex(([otherKey, otherValue]) => {\n const mark = held.log.length;\n if (equalValues(key, otherKey, held) && equalValues(value, otherValue, held)) return true;\n releasePairs(held, mark);\n return false;\n });\n if (at < 0) return false;\n free.splice(at, 1);\n }\n return true;\n}\n\n/** The comparison of two objects with the same prototype. */\nfunction equalObjects(a: any, b: any, held: HeldPairs): boolean {\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!equalValues(a[i], b[i], held)) return false;\n }\n return true;\n }\n if (isBinary(a)) return equalElements(bytesOf(a), bytesOf(b));\n if (ArrayBuffer.isView(a)) return equalElements(a as unknown as ArrayLike<unknown>, b);\n if (isOpaque(a)) return false;\n if (a instanceof Date && !sameValueZero(a.getTime(), b.getTime())) return false;\n if (a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags)) return false;\n if (a instanceof Error && !(a.name === b.name && a.message === b.message && equalValues(a.cause, b.cause, held))) return false;\n if (isBoxed(a) && !sameValueZero(a.valueOf(), b.valueOf())) return false;\n if ((a instanceof Map || a instanceof Set) && !equalEntries(a, b, held)) return false;\n return equalKeys(a, b, held);\n}\n\n/**\n * The comparison of two values. A pair stays held after it passes, so a shared or cyclic part\n * costs one visit. A failure ends the whole comparison, or the try in `equalEntries`, which\n * releases its pairs.\n */\nfunction equalValues(a: unknown, b: unknown, held: HeldPairs): boolean {\n if (sameValueZero(a, b)) return true;\n if (!isObject(a) || !isObject(b)) return false;\n if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;\n let partners = held.partners.get(a);\n if (partners?.has(b)) return true;\n if (partners === undefined) {\n partners = new Set();\n held.partners.set(a, partners);\n }\n partners.add(b);\n held.log.push([a, b]);\n return equalObjects(a, b, held);\n}\n\n/**\n * Deep structural equality. This relation is an equivalence: it is reflexive, symmetric and\n * transitive, for each value.\n *\n * - Primitives compare by SameValueZero: NaN equals NaN, and 0 equals -0.\n * - Two objects must have the same prototype. So `{}` differs from `Object.create(null)`, from an\n * instance of a class with the same keys, and from an object of another realm.\n * - Arrays compare by length and by index. A hole equals `undefined`.\n * - Typed arrays compare by element. `ArrayBuffer`, `SharedArrayBuffer` and `DataView` compare by byte.\n * - `Date` compares by time, `RegExp` by source and flags, and `Error` by name, message and cause.\n * - A boxed primitive compares by its value. `Map` and `Set` compare by entries, in any order. An object key\n * matches a deep-equal key.\n * - Each other object compares by its own enumerable keys, strings and symbols, in any order. The objects above do too,\n * except arrays and binary data.\n * - Functions, `Promise`, `WeakMap`, `WeakSet` and `WeakRef` compare by identity.\n * - Cycles are safe: two cyclic values are equal when they unfold to the same infinite tree.\n *\n * The recursion follows the depth of the data, so a very deep value can exhaust the stack.\n * `defaultHash` agrees with this relation: two equal values have one hash.\n */\nexport const deepEq: Eq<any> = (a, b): boolean => equalValues(a, b, { partners: new Map(), log: [] });\n\n/**\n * Equality by comparing a specific property.\n *\n * @example\n * const userEq = eqBy<User, 'id'>('id')\n * // or with accessor function:\n * const userEq = eqBy<User>((u) => u.id)\n */\nexport const eqBy = <T, K extends keyof T = keyof T>(\n keyOrFn: K | ((value: T) => any)\n): Eq<T> => {\n const accessor = typeof keyOrFn === \"function\" ? keyOrFn : (v: T) => v[keyOrFn];\n return (a, b) => accessor(a) === accessor(b);\n};\n\n// ============================================================================\n// Default Hashing\n// ============================================================================\n\n/** The hash of one primitive or function. */\nfunction hashPrimitive(value: unknown): number {\n if (value === null) return 0;\n if (value === undefined) return 1;\n switch (typeof value) {\n case \"boolean\":\n return value ? 1 : 0;\n case \"number\":\n return hashNumber(value);\n case \"string\":\n return hashString(value);\n case \"symbol\":\n return hashString(value.toString());\n case \"bigint\":\n return hashString(value.toString());\n default:\n return 2;\n }\n}\n\n/** The levels of an object that `defaultHash` reads. A cyclic value unfolds to this depth and stops. */\nconst HASH_DEPTH = 16;\n\n/** The hashes of one call, by object and by remaining depth. A shared part costs one visit per depth. */\ntype HashMemo = Map<object, number[]>;\n\n/** This function adds one hash to a running hash. The result depends on the order. */\nconst mix = (hash: number, part: number): number => (Math.imul(hash, 31) + part) | 0;\n\n/** The finalizer of MurmurHash3. It makes a sum of entries depend on each pair, not on each half. */\nfunction scramble(hash: number): number {\n let mixed = hash ^ (hash >>> 16);\n mixed = Math.imul(mixed, 0x85ebca6b);\n mixed ^= mixed >>> 13;\n mixed = Math.imul(mixed, 0xc2b2ae35);\n return mixed ^ (mixed >>> 16);\n}\n\n/** The start values of the kinds. Two kinds do not compare equal, so their hashes can differ. */\nconst KIND = { array: 3, binary: 5, elements: 7, opaque: 11, record: 13 } as const;\n\nconst hashAt = (value: unknown, depth: number, memo: HashMemo): number =>\n isObject(value) ? hashObject(value, depth, memo) : hashPrimitive(value);\n\nfunction hashElements(start: number, elements: ArrayLike<unknown>): number {\n let hash = start;\n for (let i = 0; i < elements.length; i++) hash = mix(hash, hashPrimitive(elements[i]));\n return hash;\n}\n\n/** The sum of the entries of a map or a set. A sum does not depend on the order of the entries. */\nfunction hashEntries(value: Map<unknown, unknown> | Set<unknown>, depth: number, memo: HashMemo): number {\n let sum = 0;\n for (const [key, entry] of value.entries()) sum = (sum + scramble(mix(hashAt(key, depth, memo), hashAt(entry, depth, memo)))) | 0;\n return sum;\n}\n\n/** The sum of the own enumerable keys and their values, as `equalKeys` reads them. */\nfunction hashKeys(value: any, depth: number, memo: HashMemo): number {\n let sum = 0;\n for (const key of enumerableKeys(value)) sum = (sum + scramble(mix(hashPrimitive(key), hashAt(value[key], depth, memo)))) | 0;\n return sum;\n}\n\n/** The hash of the fields of one object. This function reads only what `equalObjects` reads. */\nfunction hashFields(value: any, depth: number, memo: HashMemo): number {\n if (Array.isArray(value)) {\n let hash: number = KIND.array;\n for (let i = 0; i < value.length; i++) hash = mix(hash, hashAt(value[i], depth, memo));\n return hash;\n }\n if (isBinary(value)) return hashElements(KIND.binary, bytesOf(value));\n if (ArrayBuffer.isView(value)) return hashElements(KIND.elements, value as unknown as ArrayLike<unknown>);\n if (isOpaque(value)) return KIND.opaque;\n let hash: number = KIND.record;\n if (value instanceof Date) hash = mix(hash, hashNumber(value.getTime()));\n if (value instanceof RegExp) hash = mix(mix(hash, hashString(value.source)), hashString(value.flags));\n if (value instanceof Error) {\n hash = mix(mix(mix(hash, hashAt(value.name, depth, memo)), hashAt(value.message, depth, memo)), hashAt(value.cause, depth, memo));\n }\n if (isBoxed(value)) hash = mix(hash, hashPrimitive(value.valueOf()));\n if (value instanceof Map || value instanceof Set) hash = mix(hash, hashEntries(value, depth, memo));\n return mix(hash, hashKeys(value, depth, memo));\n}\n\n/** The hash of one object at one depth. The depth falls with each level, so a cycle ends. */\nfunction hashObject(value: object, depth: number, memo: HashMemo): number {\n if (depth === 0) return 0;\n let byDepth = memo.get(value);\n if (byDepth === undefined) {\n byDepth = [];\n memo.set(value, byDepth);\n }\n const known = byDepth[depth];\n if (known !== undefined) return known;\n const hash = hashFields(value, depth - 1, memo);\n byDepth[depth] = hash;\n return hash;\n}\n\n/**\n * This function is the default hash of a key. It agrees with `deepEq`: when `deepEq(a, b)` is true,\n * `defaultHash(a)` equals `defaultHash(b)`. So a hash map with `deepEq` finds an equal key.\n *\n * - The hash of an object reads the same fields as `deepEq`. The order of the keys of an object,\n * and of the entries of a `Map` or a `Set`, has no effect.\n * - The hash reads 16 levels, so a cyclic or very deep value ends. Two values that differ only\n * below that depth have one hash, and `deepEq` then tells them apart.\n * - A shared part costs one visit per level, so a dense graph ends.\n * - The hash of an object can change in a new version. Do not store it.\n */\nexport const defaultHash: Hash<any> = (value: any): number =>\n isObject(value) ? hashObject(value, HASH_DEPTH, new Map()) : hashPrimitive(value);\n\n/**\n * Hash function for strings using djb2 algorithm.\n */\nexport const hashString = (str: string): number => {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) + str.charCodeAt(i); // hash * 33 + c\n hash = hash & hash; // Convert to 32-bit integer\n }\n return hash >>> 0; // Convert to unsigned\n};\n\n/**\n * Hash function for numbers.\n */\nexport const hashNumber = (num: number): number => {\n if (Number.isNaN(num)) return 0;\n if (!Number.isFinite(num)) return num > 0 ? 1 : -1;\n\n // For integers, use the number itself\n if (Number.isInteger(num)) {\n return num | 0; // Convert to 32-bit int\n }\n\n // For floats, hash the string representation\n return hashString(num.toString());\n};\n\n/**\n * This function combines hash values into one hash.\n * Useful for hashing objects with multiple fields.\n *\n * @example\n * const pointHash: Hash<Point> = (p) =>\n * combineHashes(hashNumber(p.x), hashNumber(p.y))\n */\nexport const combineHashes = (...hashes: number[]): number => {\n let combined = 0;\n for (const hash of hashes) {\n combined = ((combined << 5) - combined) + hash;\n combined = combined & combined; // Convert to 32-bit int\n }\n return combined >>> 0; // Convert to unsigned\n};\n\n/**\n * This function makes a hash function that hashes by a property.\n *\n * @example\n * const userHash = hashBy<User>((u) => u.id)\n */\nexport const hashBy = <T>(accessor: (value: T) => any): Hash<T> => {\n return (value) => defaultHash(accessor(value));\n};\n\n// ============================================================================\n// Default Comparison\n// ============================================================================\n\n/** This function gives the place of `null` and `undefined` in the order of `defaultCompare`: `null`, then `undefined`, then each other value. */\nconst nullishRank = (value: unknown): number => (value === null ? 0 : value === undefined ? 1 : 2);\n\n/**\n * This comparator gives the natural order of primitives.\n * - `null` comes first, then `undefined`, then each other value.\n * - Numbers and dates compare as `numberCompare` and `dateCompare` compare them.\n * - Strings compare by `localeCompare`, and `false` comes before `true`.\n * - Two values of different types compare by their text, with `String`.\n */\nexport const defaultCompare: Compare<any> = (a, b) => {\n if (a === b) return 0;\n const nullish = nullishRank(a) - nullishRank(b);\n if (nullish !== 0) return nullish;\n\n // Handle dates\n if (a instanceof Date && b instanceof Date) {\n return dateCompare(a, b);\n }\n\n // Handle numbers\n if (typeof a === \"number\" && typeof b === \"number\") {\n return numberCompare(a, b);\n }\n\n // Handle strings\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a.localeCompare(b);\n }\n\n // Handle booleans\n if (typeof a === \"boolean\" && typeof b === \"boolean\") {\n return a === b ? 0 : a ? 1 : -1;\n }\n\n // Fallback: convert to string and compare\n return String(a).localeCompare(String(b));\n};\n\n/**\n * This comparator gives the order of numbers by value. It gives -1, 0 or 1.\n * - `NaN` comes first, and two `NaN` values give 0.\n * - Two equal infinities give 0, and 0 equals -0.\n */\nexport const numberCompare: Compare<number> = (a, b) => {\n if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : -1;\n if (Number.isNaN(b)) return 1;\n return a < b ? -1 : a > b ? 1 : 0;\n};\n\n/**\n * String comparison using locale-aware sorting.\n */\nexport const stringCompare: Compare<string> = (a, b) => a.localeCompare(b);\n\n/**\n * Case-insensitive string comparison.\n */\nexport const stringCompareIgnoreCase: Compare<string> = (a, b) =>\n a.toLowerCase().localeCompare(b.toLowerCase());\n\n/**\n * This comparator gives the order of dates by time, with `numberCompare`. An invalid date has the time `NaN`, so it comes\n * first, and two invalid dates give 0.\n */\nexport const dateCompare: Compare<Date> = (a, b) => numberCompare(a.getTime(), b.getTime());\n\n/**\n * Boolean comparison (false < true).\n */\nexport const booleanCompare: Compare<boolean> = (a, b) =>\n a === b ? 0 : a ? 1 : -1;\n\n// ============================================================================\n// Comparator Combinators\n// ============================================================================\n\n/**\n * This function reverses a comparator.\n *\n * @example\n * const descending = reversed(numberCompare)\n */\nexport const reversed = <T>(compare: Compare<T>): Compare<T> =>\n (a, b) => compare(b, a);\n\n/**\n * This function makes a comparator that compares by a specific property or function.\n *\n * @example\n * const byAge = comparing<Person>((p) => p.age)\n * const byName = comparing<Person, 'name'>('name')\n */\nexport const comparing = <T, K extends keyof T = keyof T>(\n keyOrFn: K | ((value: T) => any),\n compare: Compare<any> = defaultCompare\n): Compare<T> => {\n const accessor = typeof keyOrFn === \"function\" ? keyOrFn : (v: T) => v[keyOrFn];\n return (a, b) => compare(accessor(a), accessor(b));\n};\n\n/**\n * Chains comparators. If the first comparator gives 0 (equal),\n * tries the next comparator, and so on.\n *\n * @example\n * const userCompare = thenComparing(\n * comparing<User>('lastName'),\n * comparing<User>('firstName'),\n * comparing<User>('age')\n * )\n */\nexport const thenComparing = <T>(...comparators: Compare<T>[]): Compare<T> => {\n return (a, b) => {\n for (const compare of comparators) {\n const result = compare(a, b);\n if (result !== 0) return result;\n }\n return 0;\n };\n};\n\n/**\n * This function makes a comparator that treats null/undefined as less than all other values.\n *\n * @example\n * const compare = nullsFirst(numberCompare)\n */\nexport const nullsFirst = <T>(compare: Compare<T>): Compare<T | null | undefined> => {\n return (a, b) => {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n return compare(a, b);\n };\n};\n\n/**\n * This function makes a comparator that treats null/undefined as greater than all other values.\n *\n * @example\n * const compare = nullsLast(numberCompare)\n */\nexport const nullsLast = <T>(compare: Compare<T>): Compare<T | null | undefined> => {\n return (a, b) => {\n if (a == null && b == null) return 0;\n if (a == null) return 1;\n if (b == null) return -1;\n return compare(a, b);\n };\n};\n\n/**\n * This function makes a comparator from a key extraction function.\n * Elements are compared by their extracted keys.\n *\n * @example\n * const byLength = comparingKey<string>((s) => s.length)\n */\nexport const comparingKey = <T, K>(\n keyExtractor: (value: T) => K,\n keyCompare: Compare<K> = defaultCompare\n): Compare<T> => {\n return (a, b) => keyCompare(keyExtractor(a), keyExtractor(b));\n};\n","/**\n * ArrayList implementation - A dynamic array-backed list.\n *\n * This module gives O(1) indexed access and amortized O(1) append.\n * Mirrors java.util.ArrayList.\n *\n * @example\n * const list = arrayList<number>()\n * list.add(1)\n * list.add(2)\n * list.add(3)\n * console.log(list.get(1)) // 2\n */\n\nimport type { List, RandomAccess } from \"../interfaces/list.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Options for making an ArrayList.\n */\nexport interface ArrayListOptions<T> {\n /**\n * Initial capacity of the underlying array.\n * @default 10\n */\n initialCapacity?: number;\n\n /**\n * Equality function for comparing elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n}\n\n/**\n * ArrayList<T> - Resizable array implementation of the List interface.\n *\n * This class gives fast random access (O(1)) and fast append (amortized O(1)).\n * Insertion and removal in the middle shift elements (O(n)).\n *\n * This is the most commonly used list implementation.\n */\nexport class ArrayList<T> implements List<T>, RandomAccess {\n private _array: T[];\n private _size: number;\n private readonly _eq: Eq<T>;\n\n readonly supportsRandomAccess = true as const;\n\n constructor(options: ArrayListOptions<T> = {}) {\n const { initialCapacity = 10, eq = defaultEq } = options;\n this._array = new Array(initialCapacity);\n this._size = 0;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size and capacity\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Current capacity of the underlying array.\n */\n get capacity(): number {\n return this._array.length;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Indexed access\n // ========================================================================\n\n get(index: number): T {\n this.checkIndex(index);\n return this._array[index]!;\n }\n\n set(index: number, element: T): T {\n this.checkIndex(index);\n const old = this._array[index]!;\n this._array[index] = element;\n return old!;\n }\n\n // ========================================================================\n // Search\n // ========================================================================\n\n contains(element: T): boolean {\n return this.indexOf(element) !== -1;\n }\n\n indexOf(element: T, fromIndex: number = 0): number {\n if (fromIndex < 0) fromIndex = 0;\n for (let i = fromIndex; i < this._size; i++) {\n if (this._eq(this._array[i]!, element)) {\n return i;\n }\n }\n return -1;\n }\n\n lastIndexOf(element: T, fromIndex?: number): number {\n const start =\n fromIndex !== undefined\n ? Math.min(fromIndex, this._size - 1)\n : this._size - 1;\n for (let i = start; i >= 0; i--) {\n if (this._eq(this._array[i]!, element)) {\n return i;\n }\n }\n return -1;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) return false;\n }\n return true;\n }\n\n // ========================================================================\n // Addition\n // ========================================================================\n\n add(element: T): boolean {\n this.ensureCapacity(this._size + 1);\n this._array[this._size++] = element;\n return true;\n }\n\n push(element: T): void {\n this.add(element);\n }\n\n unshift(element: T): void {\n this.insert(0, element);\n }\n\n insert(index: number, element: T): void {\n this.checkInsertIndex(index);\n this.ensureCapacity(this._size + 1);\n\n // Shift elements to the right\n for (let i = this._size; i > index; i--) {\n this._array[i] = this._array[i - 1]!;\n }\n\n this._array[index] = element;\n this._size++;\n }\n\n insertAll(index: number, other: Iterable<T>): boolean {\n this.checkInsertIndex(index);\n const elements = Array.isArray(other) ? other : Array.from(other);\n if (elements.length === 0) return false;\n\n this.ensureCapacity(this._size + elements.length);\n\n // Shift existing elements to the right\n for (let i = this._size - 1; i >= index; i--) {\n this._array[i + elements.length] = this._array[i]!;\n }\n\n // Insert new elements\n for (let i = 0; i < elements.length; i++) {\n this._array[index + i] = elements[i];\n }\n\n this._size += elements.length;\n return true;\n }\n\n addAll(other: Iterable<T>): boolean {\n const elements = Array.isArray(other) ? other : Array.from(other);\n if (elements.length === 0) return false;\n\n this.ensureCapacity(this._size + elements.length);\n\n for (const element of elements) {\n this._array[this._size++] = element;\n }\n\n return true;\n }\n\n // ========================================================================\n // Removal\n // ========================================================================\n\n remove(element: T): boolean {\n const index = this.indexOf(element);\n if (index === -1) return false;\n this.removeAt(index);\n return true;\n }\n\n removeAt(index: number): T {\n this.checkIndex(index);\n const old = this._array[index]!;\n\n // Shift elements to the left\n for (let i = index; i < this._size - 1; i++) {\n this._array[i] = this._array[i + 1]!;\n }\n\n this._size--;\n // Clear the last element to allow GC\n this._array[this._size] = undefined as any;\n\n return old;\n }\n\n pop(): T {\n if (this.isEmpty) {\n throw new Error(\"Cannot pop from empty list\");\n }\n return this.removeAt(this._size - 1);\n }\n\n shift(): T {\n if (this.isEmpty) {\n throw new Error(\"Cannot shift from empty list\");\n }\n return this.removeAt(0);\n }\n\n removeRange(fromIndex: number, toIndex: number): void {\n this.checkRange(fromIndex, toIndex);\n const numToRemove = toIndex - fromIndex;\n if (numToRemove === 0) return;\n\n // Shift elements to the left\n for (let i = toIndex; i < this._size; i++) {\n this._array[i - numToRemove] = this._array[i]!;\n }\n\n // Clear removed elements\n for (let i = this._size - numToRemove; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n\n this._size -= numToRemove;\n }\n\n removeAll(other: Iterable<T>): boolean {\n const toRemove = new Set<T>();\n for (const element of other) {\n toRemove.add(element);\n }\n\n let writeIndex = 0;\n let modified = false;\n\n for (let readIndex = 0; readIndex < this._size; readIndex++) {\n const element = this._array[readIndex]!;\n let shouldRemove = false;\n\n // Check if element matches any in toRemove using custom equality\n for (const removeElement of toRemove) {\n if (this._eq(element, removeElement)) {\n shouldRemove = true;\n modified = true;\n break;\n }\n }\n\n if (!shouldRemove) {\n this._array[writeIndex++] = element;\n }\n }\n\n // Clear remaining elements\n for (let i = writeIndex; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n\n this._size = writeIndex;\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = Array.from(other);\n let writeIndex = 0;\n let modified = false;\n\n for (let readIndex = 0; readIndex < this._size; readIndex++) {\n const element = this._array[readIndex]!;\n let shouldRetain = false;\n\n // Check if element matches any in toRetain using custom equality\n for (const retainElement of toRetain) {\n if (this._eq(element, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n\n if (shouldRetain) {\n this._array[writeIndex++] = element;\n } else {\n modified = true;\n }\n }\n\n // Clear remaining elements\n for (let i = writeIndex; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n\n this._size = writeIndex;\n return modified;\n }\n\n clear(): void {\n // Clear all elements to allow GC\n for (let i = 0; i < this._size; i++) {\n this._array[i] = undefined as any;\n }\n this._size = 0;\n }\n\n // ========================================================================\n // Ordering\n // ========================================================================\n\n sort(compare: Compare<T> = defaultCompare): void {\n // Sort only the used portion of the array\n const slice = this._array.slice(0, this._size);\n slice.sort(compare);\n for (let i = 0; i < this._size; i++) {\n this._array[i] = slice[i]!;\n }\n }\n\n reverse(): void {\n let left = 0;\n let right = this._size - 1;\n while (left < right) {\n const temp = this._array[left]!;\n this._array[left] = this._array[right]!;\n this._array[right] = temp;\n left++;\n right--;\n }\n }\n\n // ========================================================================\n // Views\n // ========================================================================\n\n first(): T {\n if (this.isEmpty) {\n throw new Error(\"List is empty\");\n }\n return this._array[0]!;\n }\n\n last(): T {\n if (this.isEmpty) {\n throw new Error(\"List is empty\");\n }\n return this._array[this._size - 1]!;\n }\n\n subList(fromIndex: number, toIndex: number): List<T> {\n this.checkRange(fromIndex, toIndex);\n // For now, return a copy. Later we can implement a view.\n const sub = new ArrayList<T>({ eq: this._eq });\n for (let i = fromIndex; i < toIndex; i++) {\n sub.add(this._array[i]!);\n }\n return sub;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n for (let i = 0; i < this._size; i++) {\n yield this._array[i]!;\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n for (let i = 0; i < this._size; i++) {\n action(this._array[i]!, i);\n }\n }\n\n toArray(): T[] {\n return this._array.slice(0, this._size);\n }\n\n // ========================================================================\n // Capacity management\n // ========================================================================\n\n /**\n * This method makes sure that the capacity is at least the specified minimum.\n */\n ensureCapacity(minCapacity: number): void {\n if (minCapacity <= this._array.length) return;\n\n // Grow by 1.5x or to minCapacity, whichever is larger\n const newCapacity = Math.max(\n minCapacity,\n Math.floor(this._array.length * 1.5) + 1\n );\n\n const newArray = new Array(newCapacity);\n for (let i = 0; i < this._size; i++) {\n newArray[i] = this._array[i];\n }\n this._array = newArray;\n }\n\n /**\n * This method trims the capacity to the current size to minimize memory usage.\n */\n trimToSize(): void {\n if (this._size < this._array.length) {\n this._array = this._array.slice(0, this._size);\n }\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n private checkIndex(index: number): void {\n if (index < 0 || index >= this._size) {\n throw new RangeError(\n `Index ${index} out of bounds for size ${this._size}`\n );\n }\n }\n\n private checkInsertIndex(index: number): void {\n if (index < 0 || index > this._size) {\n throw new RangeError(\n `Index ${index} out of bounds for insert (size ${this._size})`\n );\n }\n }\n\n private checkRange(fromIndex: number, toIndex: number): void {\n if (fromIndex < 0 || toIndex > this._size || fromIndex > toIndex) {\n throw new RangeError(\n `Invalid range [${fromIndex}, ${toIndex}) for size ${this._size}`\n );\n }\n }\n}\n\n/**\n * Factory function to make an ArrayList.\n *\n * @example\n * const list = arrayList<number>()\n * const listWithEq = arrayList<User>({ eq: (a, b) => a.id === b.id })\n * const listFromArray = arrayList([1, 2, 3])\n */\nexport function arrayList<T>(\n optionsOrElements?: ArrayListOptions<T> | Iterable<T>\n): ArrayList<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const list = new ArrayList<T>();\n list.addAll(optionsOrElements as Iterable<T>);\n return list;\n }\n\n const list = new ArrayList<T>(optionsOrElements as ArrayListOptions<T>);\n return list;\n}\n","/**\n * ArrayDeque implementation - A ring buffer backed double-ended queue.\n *\n * This module gives O(1) insertion and removal at both ends.\n * More efficient than ArrayList for queue/stack operations.\n * Mirrors java.util.ArrayDeque.\n *\n * @example\n * const deque = arrayDeque<number>()\n * deque.addFirst(1)\n * deque.addLast(2)\n * deque.removeFirst() // 1\n */\n\nimport type { Deque } from \"../interfaces/queue.js\";\nimport type { Eq } from \"../core/traits.js\";\nimport { defaultEq } from \"../utils/defaults.js\";\n\n/**\n * Options for making an ArrayDeque.\n */\nexport interface ArrayDequeOptions<T> {\n /**\n * Initial capacity of the underlying array.\n * This value must be a power of 2 for efficient modulo operations.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * Equality function for comparing elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n}\n\n/**\n * ArrayDeque<T> - Ring buffer implementation of Deque.\n *\n * This class uses a circular array to give O(1) operations at both ends.\n * The array grows automatically when full.\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class ArrayDeque<T> implements Deque<T> {\n private _elements: (T | undefined)[];\n private _head: number; // Index of first element\n private _tail: number; // Index where next element will be added\n private readonly _eq: Eq<T>;\n\n constructor(options: ArrayDequeOptions<T> = {}) {\n const { initialCapacity = 16, eq = defaultEq } = options;\n // Ensure capacity is a power of 2 for efficient modulo using bitwise AND\n const capacity = this.nextPowerOfTwo(Math.max(8, initialCapacity));\n this._elements = new Array(capacity);\n this._head = 0;\n this._tail = 0;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n // Handle wraparound: (tail - head) & mask\n return (this._tail - this._head) & (this._elements.length - 1);\n }\n\n get isEmpty(): boolean {\n return this._head === this._tail;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Front operations (head)\n // ========================================================================\n\n addFirst(element: T): void {\n this._head = (this._head - 1) & (this._elements.length - 1);\n this._elements[this._head] = element;\n if (this._head === this._tail) {\n this.grow();\n }\n }\n\n offerFirst(element: T): boolean {\n this.addFirst(element);\n return true;\n }\n\n removeFirst(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n return this.pollFirst()!;\n }\n\n pollFirst(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n const element = this._elements[this._head];\n this._elements[this._head] = undefined;\n this._head = (this._head + 1) & (this._elements.length - 1);\n return element;\n }\n\n peekFirst(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n return this._elements[this._head]!;\n }\n\n peekFirstOrUndefined(): T | undefined {\n return this.isEmpty ? undefined : this._elements[this._head];\n }\n\n // ========================================================================\n // Back operations (tail)\n // ========================================================================\n\n addLast(element: T): void {\n this._elements[this._tail] = element;\n this._tail = (this._tail + 1) & (this._elements.length - 1);\n if (this._tail === this._head) {\n this.grow();\n }\n }\n\n offerLast(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n removeLast(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n return this.pollLast()!;\n }\n\n pollLast(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n this._tail = (this._tail - 1) & (this._elements.length - 1);\n const element = this._elements[this._tail];\n this._elements[this._tail] = undefined;\n return element;\n }\n\n peekLast(): T {\n if (this.isEmpty) {\n throw new Error(\"Deque is empty\");\n }\n const lastIndex = (this._tail - 1) & (this._elements.length - 1);\n return this._elements[lastIndex]!;\n }\n\n peekLastOrUndefined(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n const lastIndex = (this._tail - 1) & (this._elements.length - 1);\n return this._elements[lastIndex];\n }\n\n // ========================================================================\n // Stack operations (LIFO at the end, as on a JavaScript array)\n // ========================================================================\n\n // push and pop work at the end, and shift/unshift at the front, in every collection of this\n // package. Before, they worked at the front here (the Java Deque rule), so a LinkedList used\n // as a List reversed the pushed elements (ARCHITECTURE-PROPOSALS P8).\n push(element: T): void {\n this.addLast(element);\n }\n\n pop(): T {\n return this.removeLast();\n }\n\n // ========================================================================\n // Queue operations (FIFO - add last, remove first)\n // ========================================================================\n\n offer(element: T): boolean {\n return this.offerLast(element);\n }\n\n poll(): T {\n return this.removeFirst();\n }\n\n peek(): T {\n return this.peekFirst();\n }\n\n peekOrUndefined(): T | undefined {\n return this.peekFirstOrUndefined();\n }\n\n pollOrUndefined(): T | undefined {\n return this.pollFirst();\n }\n\n enqueue(element: T): boolean {\n return this.offer(element);\n }\n\n dequeue(): T {\n return this.poll();\n }\n\n // ========================================================================\n // Collection operations\n // ========================================================================\n\n add(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n this.addLast(element);\n modified = true;\n }\n return modified;\n }\n\n contains(element: T): boolean {\n for (const item of this) {\n if (this._eq(item, element)) {\n return true;\n }\n }\n return false;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n remove(element: T): boolean {\n // Linear search for the first occurrence\n const mask = this._elements.length - 1;\n const size = this.size;\n for (let offset = 0; offset < size; offset++) {\n if (this._eq(this._elements[(this._head + offset) & mask]!, element)) {\n this.removeAtOffset(offset);\n return true;\n }\n }\n return false;\n }\n\n /**\n * This method removes the element at a position from the head. The shorter side moves one place.\n * (Before, a bitwise expression chose the side, and it was not a valid test.)\n */\n private removeAtOffset(offset: number): void {\n const mask = this._elements.length - 1;\n const size = this.size;\n if (offset < size / 2) {\n // Move the elements before it one place toward the tail\n for (let i = offset; i > 0; i--) {\n this._elements[(this._head + i) & mask] = this._elements[(this._head + i - 1) & mask];\n }\n this._elements[this._head] = undefined;\n this._head = (this._head + 1) & mask;\n } else {\n // Move the elements after it one place toward the head\n for (let i = offset; i < size - 1; i++) {\n this._elements[(this._head + i) & mask] = this._elements[(this._head + i + 1) & mask];\n }\n this._tail = (this._tail - 1) & mask;\n this._elements[this._tail] = undefined;\n }\n }\n\n\n removeAll(other: Iterable<T>): boolean {\n const toRemove = new Set<T>();\n for (const element of other) {\n toRemove.add(element);\n }\n\n let modified = false;\n for (const element of toRemove) {\n while (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = new Set(other);\n const newDeque = new ArrayDeque<T>({ eq: this._eq });\n\n for (const element of this) {\n let shouldRetain = false;\n for (const retainElement of toRetain) {\n if (this._eq(element, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n if (shouldRetain) {\n newDeque.addLast(element);\n }\n }\n\n const modified = newDeque.size !== this.size;\n this._elements = newDeque._elements;\n this._head = newDeque._head;\n this._tail = newDeque._tail;\n\n return modified;\n }\n\n clear(): void {\n // Clear all elements for GC\n let index = this._head;\n while (index !== this._tail) {\n this._elements[index] = undefined;\n index = (index + 1) & (this._elements.length - 1);\n }\n this._head = 0;\n this._tail = 0;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n let index = this._head;\n while (index !== this._tail) {\n yield this._elements[index]!;\n index = (index + 1) & (this._elements.length - 1);\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let arrayIndex = this._head;\n let logicalIndex = 0;\n while (arrayIndex !== this._tail) {\n action(this._elements[arrayIndex]!, logicalIndex);\n arrayIndex = (arrayIndex + 1) & (this._elements.length - 1);\n logicalIndex++;\n }\n }\n\n toArray(): T[] {\n const result: T[] = [];\n for (const element of this) {\n result.push(element);\n }\n return result;\n }\n\n // ========================================================================\n // Capacity management\n // ========================================================================\n\n /**\n * This method doubles the capacity of the deque.\n */\n private grow(): void {\n const oldCapacity = this._elements.length;\n const newCapacity = oldCapacity << 1; // Double capacity\n\n if (newCapacity < 0) {\n throw new Error(\"Deque too large\");\n }\n\n const newElements = new Array(newCapacity);\n\n // Copy elements from head to end of old array\n const rightSize = oldCapacity - this._head;\n for (let i = 0; i < rightSize; i++) {\n newElements[i] = this._elements[this._head + i];\n }\n\n // Copy wrapped elements from start of old array\n const leftSize = this._head;\n for (let i = 0; i < leftSize; i++) {\n newElements[rightSize + i] = this._elements[i];\n }\n\n // grow() runs when the array is full: head === tail and every slot holds an element. Then\n // `size` computes 0, so the old `this._tail = size` lost every element (BUGS-2026-07 C8).\n this._elements = newElements;\n this._head = 0;\n this._tail = oldCapacity;\n }\n\n /**\n * This method gives the next power of 2 >= n.\n */\n private nextPowerOfTwo(n: number): number {\n if (n <= 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n return n + 1;\n }\n\n // ========================================================================\n // Inspection\n // ========================================================================\n\n /**\n * This value is the current capacity of the underlying array.\n */\n get capacity(): number {\n return this._elements.length;\n }\n\n /**\n * This method gives a string representation for debugging.\n */\n toString(): string {\n return `ArrayDeque[${this.toArray().join(\", \")}]`;\n }\n}\n\n/**\n * Factory function to make an ArrayDeque.\n *\n * @example\n * const deque = arrayDeque<number>()\n * const dequeFromArray = arrayDeque([1, 2, 3])\n * const dequeWithOptions = arrayDeque<string>({ initialCapacity: 32 })\n */\nexport function arrayDeque<T>(\n optionsOrElements?: ArrayDequeOptions<T> | Iterable<T>\n): ArrayDeque<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const deque = new ArrayDeque<T>();\n deque.addAll(optionsOrElements as Iterable<T>);\n return deque;\n }\n\n return new ArrayDeque<T>(optionsOrElements as ArrayDequeOptions<T>);\n}\n","/**\n * HashMap implementation - A hash table with custom equality and hashing.\n *\n * This module gives O(1) average case lookup, insertion, and deletion.\n * This module supports custom equality and hash functions for keys.\n * Mirrors java.util.HashMap.\n *\n * @example\n * const map = hashMap<string, number>()\n * map.set('one', 1)\n * map.set('two', 2)\n * console.log(map.get('one')) // 1\n *\n * // Custom equality for object keys\n * const userMap = hashMap<User, Data>({\n * keyEq: (a, b) => a.id === b.id,\n * keyHash: (u) => hashString(u.id)\n * })\n */\n\nimport type { MapLike, Entry } from \"../interfaces/map.js\";\nimport type { Eq, Hash } from \"../core/traits.js\";\nimport { defaultEq, defaultHash } from \"../utils/defaults.js\";\n\n/**\n * Internal entry node for hash buckets.\n */\ninterface Node<K, V> {\n key: K;\n value: V;\n hash: number;\n next: Node<K, V> | null;\n}\n\n/**\n * Options for making a HashMap.\n */\nexport interface HashMapOptions<K, V> {\n /**\n * Initial capacity (number of buckets).\n * This value must be a power of 2.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * This option is the load factor threshold for a resize, from 0 to 1.\n * When size > capacity * loadFactor, the map resizes.\n * @default 0.75\n */\n loadFactor?: number;\n\n /**\n * Equality function for keys.\n * @default defaultEq (===)\n */\n keyEq?: Eq<K>;\n\n /**\n * Hash function for keys.\n * @default defaultHash\n */\n keyHash?: Hash<K>;\n\n /**\n * Equality function for values (used in containsValue).\n * @default defaultEq (===)\n */\n valueEq?: Eq<V>;\n}\n\n/**\n * HashMap<K, V> - Hash table implementation with custom equality/hashing.\n *\n * This class uses separate chaining for collision resolution.\n * The map resizes when its load factor is more than the threshold.\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class HashMap<K, V> implements MapLike<K, V> {\n private _buckets: (Node<K, V> | null)[];\n private _size: number;\n private readonly _loadFactor: number;\n private readonly _keyEq: Eq<K>;\n private readonly _keyHash: Hash<K>;\n private readonly _valueEq: Eq<V>;\n private _threshold: number;\n /**\n * The count of structural changes (a key added or removed, a clear, a resize). An iterator\n * records it at its start and throws when it changes. Before, a resize during iteration made\n * the iterator skip or repeat entries (BUGS-2026-07 L15).\n */\n private _modCount = 0;\n\n constructor(options: HashMapOptions<K, V> = {}) {\n const {\n initialCapacity = 16,\n loadFactor = 0.75,\n keyEq = defaultEq,\n keyHash = defaultHash,\n valueEq = defaultEq,\n } = options;\n\n const capacity = this.nextPowerOfTwo(Math.max(4, initialCapacity));\n this._buckets = new Array(capacity).fill(null);\n this._size = 0;\n this._loadFactor = loadFactor;\n this._keyEq = keyEq;\n this._keyHash = keyHash;\n this._valueEq = valueEq;\n this._threshold = Math.floor(capacity * loadFactor);\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get keyEq(): Eq<K> {\n return this._keyEq;\n }\n\n get valueEq(): Eq<V> {\n return this._valueEq;\n }\n\n // ========================================================================\n // Lookup\n // ========================================================================\n\n has(key: K): boolean {\n return this.findNode(key) !== null;\n }\n\n get(key: K): V {\n // The node, not the value, tells if the key is present: a key can have the value undefined (C8)\n const node = this.findNode(key);\n if (node === null) {\n throw new Error(`Key not found: ${key}`);\n }\n return node.value;\n }\n\n getOrUndefined(key: K): V | undefined {\n return this.findNode(key)?.value;\n }\n\n getOrDefault(key: K, defaultValue: V): V {\n const node = this.findNode(key);\n return node !== null ? node.value : defaultValue;\n }\n\n /** This method finds the node of a key, or gives `null`. */\n private findNode(key: K): Node<K, V> | null {\n const hash = this._keyHash(key);\n let node = this._buckets[this.bucketIndex(hash)] ?? null;\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) return node;\n node = node.next;\n }\n return null;\n }\n\n containsValue(value: V): boolean {\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n if (this._valueEq(node.value, value)) {\n return true;\n }\n node = node.next;\n }\n }\n return false;\n }\n\n // ========================================================================\n // Modification\n // ========================================================================\n\n set(key: K, value: V): V | undefined {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n\n // Check if key already exists\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) {\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n }\n node = node.next;\n }\n\n // Key doesn't exist, add new entry\n const newNode: Node<K, V> = {\n key,\n value,\n hash,\n next: this._buckets[index] ?? null,\n };\n this._buckets[index] = newNode;\n this._size++;\n this._modCount++;\n\n // Check if resize is needed\n if (this._size > this._threshold) {\n this.resize();\n }\n\n return undefined;\n }\n\n setIfAbsent(key: K, value: V): V {\n const existing = this.getOrUndefined(key);\n if (existing !== undefined) {\n return existing;\n }\n this.set(key, value);\n return value;\n }\n\n delete(key: K): V | undefined {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n let prev: Node<K, V> | null = null;\n\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) {\n // Found the node to delete\n if (prev === null) {\n // Node is at head of bucket\n this._buckets[index] = node.next;\n } else {\n // Node is in middle or end\n prev.next = node.next;\n }\n this._size--;\n this._modCount++;\n return node.value;\n }\n prev = node;\n node = node.next;\n }\n\n return undefined;\n }\n\n deleteEntry(key: K, value: V): boolean {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n let prev: Node<K, V> | null = null;\n\n while (node !== null) {\n if (\n node.hash === hash &&\n this._keyEq(node.key, key) &&\n this._valueEq(node.value, value)\n ) {\n // Found the entry to delete\n if (prev === null) {\n this._buckets[index] = node.next;\n } else {\n prev.next = node.next;\n }\n this._size--;\n this._modCount++;\n return true;\n }\n prev = node;\n node = node.next;\n }\n\n return false;\n }\n\n replace(key: K, value: V): V | undefined {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n\n while (node !== null) {\n if (node.hash === hash && this._keyEq(node.key, key)) {\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n }\n node = node.next;\n }\n\n return undefined;\n }\n\n replaceEntry(key: K, oldValue: V, newValue: V): boolean {\n const hash = this._keyHash(key);\n const index = this.bucketIndex(hash);\n let node = this._buckets[index] ?? null;\n\n while (node !== null) {\n if (\n node.hash === hash &&\n this._keyEq(node.key, key) &&\n this._valueEq(node.value, oldValue)\n ) {\n node.value = newValue;\n return true;\n }\n node = node.next;\n }\n\n return false;\n }\n\n // ========================================================================\n // Compute operations\n // ========================================================================\n\n computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {\n const existing = this.getOrUndefined(key);\n if (existing !== undefined) {\n return existing;\n }\n\n const newValue = mappingFunction(key);\n this.set(key, newValue);\n return newValue;\n }\n\n computeIfPresent(\n key: K,\n remappingFunction: (key: K, value: V) => V | undefined\n ): V | undefined {\n const existing = this.getOrUndefined(key);\n if (existing === undefined) {\n return undefined;\n }\n\n const newValue = remappingFunction(key, existing);\n if (newValue === undefined) {\n this.delete(key);\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n compute(\n key: K,\n remappingFunction: (key: K, value: V | undefined) => V | undefined\n ): V | undefined {\n const existing = this.getOrUndefined(key);\n const newValue = remappingFunction(key, existing);\n\n if (newValue === undefined) {\n if (existing !== undefined) {\n this.delete(key);\n }\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n merge(\n key: K,\n value: V,\n remappingFunction: (oldValue: V, newValue: V) => V | undefined\n ): V | undefined {\n const existing = this.getOrUndefined(key);\n\n if (existing === undefined) {\n this.set(key, value);\n return value;\n }\n\n const merged = remappingFunction(existing, value);\n if (merged === undefined) {\n this.delete(key);\n return undefined;\n }\n\n this.set(key, merged);\n return merged;\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n putAll(other: MapLike<K, V> | Iterable<Entry<K, V>>): void {\n for (const entry of other) {\n this.set(entry.key, entry.value);\n }\n }\n\n clear(): void {\n this._buckets.fill(null);\n this._size = 0;\n this._modCount++;\n }\n\n // ========================================================================\n // Views\n // ========================================================================\n\n *keys(): IterableIterator<K> {\n const expected = this._modCount;\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n yield node.key;\n this.checkUnchanged(expected);\n node = node.next;\n }\n }\n }\n\n *values(): IterableIterator<V> {\n const expected = this._modCount;\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n yield node.value;\n this.checkUnchanged(expected);\n node = node.next;\n }\n }\n }\n\n *entries(): IterableIterator<Entry<K, V>> {\n const expected = this._modCount;\n for (const bucket of this._buckets) {\n let node = bucket;\n while (node !== null) {\n yield { key: node.key, value: node.value };\n this.checkUnchanged(expected);\n node = node.next;\n }\n }\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<Entry<K, V>> {\n yield* this.entries();\n }\n\n forEach(action: (value: V, key: K, map: this) => void): void {\n for (const entry of this.entries()) {\n action(entry.value, entry.key, this);\n }\n }\n\n // ========================================================================\n // Internal helpers\n // ========================================================================\n\n /** This method throws when the map changed structurally after an iterator started. */\n private checkUnchanged(expected: number): void {\n if (this._modCount !== expected) {\n throw new Error(\"HashMap changed during iteration\");\n }\n }\n\n /**\n * This method gives the bucket index for a given hash.\n */\n private bucketIndex(hash: number): number {\n // Use bitwise AND with (length - 1) for efficient modulo\n // This works because length is always a power of 2\n return hash & (this._buckets.length - 1);\n }\n\n /**\n * This method resizes the hash table to double its current capacity.\n */\n private resize(): void {\n const oldBuckets = this._buckets;\n const newCapacity = oldBuckets.length << 1; // Double capacity\n\n if (newCapacity < 0) {\n throw new Error(\"Map too large\");\n }\n\n this._buckets = new Array(newCapacity).fill(null);\n this._threshold = Math.floor(newCapacity * this._loadFactor);\n this._modCount++;\n\n // Rehash all entries\n for (const bucket of oldBuckets) {\n let node = bucket;\n while (node !== null) {\n const next = node.next;\n const index = this.bucketIndex(node.hash);\n node.next = this._buckets[index] ?? null;\n this._buckets[index] = node;\n node = next;\n }\n }\n }\n\n /**\n * This method gives the next power of 2 >= n.\n */\n private nextPowerOfTwo(n: number): number {\n if (n <= 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n return n + 1;\n }\n\n // ========================================================================\n // Inspection\n // ========================================================================\n\n /**\n * This value is the current number of buckets.\n */\n get capacity(): number {\n return this._buckets.length;\n }\n\n /**\n * This value is the current load factor (size / capacity).\n */\n get loadFactor(): number {\n return this._size / this._buckets.length;\n }\n\n /**\n * This method gives statistics about bucket distribution (for debugging).\n */\n getStats(): {\n size: number;\n capacity: number;\n loadFactor: number;\n avgChainLength: number;\n maxChainLength: number;\n emptyBuckets: number;\n } {\n let maxChainLength = 0;\n let totalChainLength = 0;\n let emptyBuckets = 0;\n\n for (const bucket of this._buckets) {\n if (bucket === null) {\n emptyBuckets++;\n } else {\n let length = 0;\n let node: Node<K, V> | null = bucket;\n while (node !== null) {\n length++;\n node = node.next;\n }\n totalChainLength += length;\n maxChainLength = Math.max(maxChainLength, length);\n }\n }\n\n return {\n size: this._size,\n capacity: this._buckets.length,\n loadFactor: this.loadFactor,\n avgChainLength: this._size > 0 ? totalChainLength / (this._buckets.length - emptyBuckets) : 0,\n maxChainLength,\n emptyBuckets,\n };\n }\n}\n\n/**\n * Factory function to make a HashMap.\n *\n * @example\n * const map = hashMap<string, number>()\n * const mapWithOptions = hashMap<User, Data>({\n * keyEq: (a, b) => a.id === b.id,\n * keyHash: (u) => hashString(u.id)\n * })\n * const mapFromEntries = hashMap([['a', 1], ['b', 2]])\n */\nexport function hashMap<K, V>(\n optionsOrEntries?: HashMapOptions<K, V> | Iterable<readonly [K, V]>\n): HashMap<K, V> {\n // Check if it's an iterable of entries\n if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {\n const map = new HashMap<K, V>();\n for (const [key, value] of optionsOrEntries as Iterable<readonly [K, V]>) {\n map.set(key, value);\n }\n return map;\n }\n\n return new HashMap<K, V>(optionsOrEntries as HashMapOptions<K, V>);\n}\n","/**\n * LinkedHashMap - HashMap that maintains insertion order.\n *\n * This module combines a hash table with a doubly-linked list to maintain predictable\n * iteration order. Mirrors java.util.LinkedHashMap.\n *\n * Key features:\n * - O(1) access, insert, delete (like HashMap)\n * - Predictable iteration order (insertion order or access order)\n * - Perfect for LRU caches when accessOrder is true\n *\n * @example\n * const map = linkedHashMap<string, number>()\n * map.set('a', 1)\n * map.set('b', 2)\n * map.set('c', 3)\n * // Iteration order: a, b, c (insertion order)\n *\n * @example\n * // LRU cache with access order\n * const lru = linkedHashMap<string, number>({ accessOrder: true })\n * lru.set('a', 1)\n * lru.set('b', 2)\n * lru.get('a') // Moves 'a' to end\n * // Iteration order: b, a (access order)\n */\n\nimport type { MapLike, Entry } from \"../interfaces/map.js\";\nimport type { Eq, Hash } from \"../core/traits.js\";\nimport { defaultEq, defaultHash } from \"../utils/defaults.js\";\n\n/**\n * An entry. It is in two lists: the chain of its hash bucket (`next`) and the order list\n * (`before`, `after`). Before, one `next` field served both lists, so the first collision or\n * resize corrupted the map (BUGS-2026-07 C10).\n */\ninterface LinkedNode<K, V> {\n key: K;\n value: V;\n hash: number;\n /** The next entry of the same hash bucket */\n next: LinkedNode<K, V> | null;\n /** The entry before this one in the iteration order */\n before: LinkedNode<K, V> | null;\n /** The entry after this one in the iteration order */\n after: LinkedNode<K, V> | null;\n}\n\n/**\n * Options for making a LinkedHashMap.\n */\nexport interface LinkedHashMapOptions<K, V> {\n /**\n * Initial capacity of the hash table.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * This option is the load factor before a resize.\n * @default 0.75\n */\n loadFactor?: number;\n\n /**\n * Equality function for keys.\n * @default defaultEq\n */\n eq?: Eq<K>;\n\n /**\n * Hash function for keys.\n * @default defaultHash\n */\n hash?: Hash<K>;\n\n /**\n * Equality function for values.\n * @default defaultEq\n */\n valueEq?: Eq<V>;\n\n /**\n * If true, maintain access order instead of insertion order.\n * Useful for LRU caches.\n * @default false\n */\n accessOrder?: boolean;\n}\n\n/**\n * LinkedHashMap<K, V> - Hash map with predictable iteration order.\n *\n * This class maintains a doubly-linked list of entries to preserve insertion order\n * (or access order if accessOrder is true).\n */\nexport class LinkedHashMap<K, V> implements MapLike<K, V> {\n private _buckets: (LinkedNode<K, V> | null)[];\n private _size: number = 0;\n private readonly _loadFactor: number;\n private readonly _eq: Eq<K>;\n private readonly _hash: Hash<K>;\n private readonly _valueEq: Eq<V>;\n private readonly _accessOrder: boolean;\n\n // Doubly-linked list sentinels\n private _head: LinkedNode<K, V> | null = null;\n private _tail: LinkedNode<K, V> | null = null;\n\n constructor(options: LinkedHashMapOptions<K, V> = {}) {\n const {\n initialCapacity = 16,\n loadFactor = 0.75,\n eq = defaultEq,\n hash = defaultHash,\n valueEq = defaultEq,\n accessOrder = false,\n } = options;\n\n this._buckets = new Array(Math.max(1, initialCapacity)).fill(null);\n this._loadFactor = loadFactor;\n this._eq = eq;\n this._hash = hash;\n this._valueEq = valueEq;\n this._accessOrder = accessOrder;\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get eq(): Eq<K> {\n return this._eq;\n }\n\n get keyEq(): Eq<K> {\n return this._eq;\n }\n\n get valueEq(): Eq<V> {\n return this._valueEq;\n }\n\n get hash(): Hash<K> {\n return this._hash;\n }\n\n // ========================================================================\n // Lookup operations\n // ========================================================================\n\n has(key: K): boolean {\n return this.getNode(key) !== null;\n }\n\n containsKey(key: K): boolean {\n return this.has(key);\n }\n\n containsValue(value: V): boolean {\n let node = this._head;\n while (node !== null) {\n if (this._valueEq(node.value, value)) {\n return true;\n }\n node = node.after;\n }\n return false;\n }\n\n get(key: K): V {\n const node = this.getNode(key);\n if (node === null) {\n throw new Error(\"Key not found\");\n }\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return node.value;\n }\n\n getOrUndefined(key: K): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return node.value;\n }\n\n getOrDefault(key: K, defaultValue: V): V {\n const node = this.getNode(key);\n if (node === null) return defaultValue;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return node.value;\n }\n\n // ========================================================================\n // Modification operations\n // ========================================================================\n\n set(key: K, value: V): V | undefined {\n const hashCode = this._hash(key);\n const index = this.getBucketIndex(hashCode);\n let node = this._buckets[index] ?? null;\n\n // Check if key already exists\n while (node !== null) {\n if (node.hash === hashCode && this._eq(node.key, key)) {\n const oldValue = node.value;\n node.value = value;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return oldValue;\n }\n node = node.next;\n }\n\n // Key doesn't exist, add new entry\n const newNode: LinkedNode<K, V> = {\n key,\n value,\n hash: hashCode,\n next: this._buckets[index] ?? null,\n before: null,\n after: null,\n };\n\n this._buckets[index] = newNode;\n this._size++;\n\n // Add to linked list\n this.addToEnd(newNode);\n\n // Resize if needed\n if (this._size > this._buckets.length * this._loadFactor) {\n this.resize();\n }\n\n return undefined;\n }\n\n setIfAbsent(key: K, value: V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return existing.value;\n }\n this.set(key, value);\n return value;\n }\n\n replace(key: K, value: V): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n const oldValue = node.value;\n node.value = value;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return oldValue;\n }\n\n replaceEntry(key: K, oldValue: V, newValue: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, oldValue)) {\n return false;\n }\n node.value = newValue;\n if (this._accessOrder) {\n this.moveToEnd(node);\n }\n return true;\n }\n\n delete(key: K): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n\n const oldValue = node.value;\n\n // Remove from bucket\n this.removeFromBucket(node);\n\n // Remove from linked list\n this.removeFromList(node);\n\n this._size--;\n return oldValue;\n }\n\n deleteEntry(key: K, value: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, value)) {\n return false;\n }\n\n // Remove from bucket\n this.removeFromBucket(node);\n\n // Remove from linked list\n this.removeFromList(node);\n\n this._size--;\n return true;\n }\n\n clear(): void {\n this._buckets = new Array(this._buckets.length).fill(null);\n this._size = 0;\n this._head = null;\n this._tail = null;\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n putAll(other: MapLike<K, V> | Iterable<Entry<K, V>>): void {\n if ('entries' in other && typeof other.entries === 'function') {\n for (const entry of other.entries()) {\n this.set(entry.key, entry.value);\n }\n } else {\n for (const entry of other as Iterable<Entry<K, V>>) {\n this.set(entry.key, entry.value);\n }\n }\n }\n\n // ========================================================================\n // Computed operations\n // ========================================================================\n\n computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return existing.value;\n }\n const value = mappingFunction(key);\n this.set(key, value);\n return value;\n }\n\n computeIfPresent(key: K, remappingFunction: (key: K, value: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n if (existing === null) return undefined;\n\n const newValue = remappingFunction(key, existing.value);\n if (newValue === undefined) {\n this.delete(key);\n return undefined;\n }\n existing.value = newValue;\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return newValue;\n }\n\n compute(key: K, remappingFunction: (key: K, value: V | undefined) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n const newValue = remappingFunction(key, existing?.value);\n\n if (newValue === undefined) {\n if (existing !== null) {\n this.delete(key);\n }\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n merge(key: K, value: V, remappingFunction: (oldValue: V, newValue: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n\n if (existing === null) {\n this.set(key, value);\n return value;\n }\n\n const merged = remappingFunction(existing.value, value);\n if (merged === undefined) {\n this.delete(key);\n return undefined;\n }\n\n existing.value = merged;\n if (this._accessOrder) {\n this.moveToEnd(existing);\n }\n return merged;\n }\n\n // ========================================================================\n // View operations\n // ========================================================================\n\n *keys(): IterableIterator<K> {\n let node = this._head;\n while (node !== null) {\n yield node.key;\n node = node.after;\n }\n }\n\n *values(): IterableIterator<V> {\n let node = this._head;\n while (node !== null) {\n yield node.value;\n node = node.after;\n }\n }\n\n *entries(): IterableIterator<Entry<K, V>> {\n let node = this._head;\n while (node !== null) {\n yield { key: node.key, value: node.value };\n node = node.after;\n }\n }\n\n *[Symbol.iterator](): Iterator<Entry<K, V>> {\n yield* this.entries();\n }\n\n forEach(action: (value: V, key: K, map: this) => void): void {\n for (const entry of this.entries()) {\n action(entry.value, entry.key, this);\n }\n }\n\n toArray(): Entry<K, V>[] {\n return Array.from(this.entries());\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n private getNode(key: K): LinkedNode<K, V> | null {\n const hashCode = this._hash(key);\n const index = this.getBucketIndex(hashCode);\n let node = this._buckets[index] ?? null;\n\n while (node !== null) {\n if (node.hash === hashCode && this._eq(node.key, key)) {\n return node;\n }\n node = node.next;\n }\n\n return null;\n }\n\n private getBucketIndex(hashCode: number): number {\n return Math.abs(hashCode) % this._buckets.length;\n }\n\n private removeFromBucket(node: LinkedNode<K, V>): void {\n const index = this.getBucketIndex(node.hash);\n let current = this._buckets[index] ?? null;\n let prev: LinkedNode<K, V> | null = null;\n\n while (current !== null) {\n if (current === node) {\n if (prev === null) {\n this._buckets[index] = current.next;\n } else {\n prev.next = current.next;\n }\n return;\n }\n prev = current;\n current = current.next;\n }\n }\n\n private addToEnd(node: LinkedNode<K, V>): void {\n node.before = this._tail;\n node.after = null;\n if (this._tail === null) this._head = node;\n else this._tail.after = node;\n this._tail = node;\n }\n\n private removeFromList(node: LinkedNode<K, V>): void {\n if (node.before !== null) node.before.after = node.after;\n else this._head = node.after;\n if (node.after !== null) node.after.before = node.before;\n else this._tail = node.before;\n node.before = node.after = null;\n }\n\n private moveToEnd(node: LinkedNode<K, V>): void {\n if (node === this._tail) return; // Already at end\n this.removeFromList(node);\n this.addToEnd(node);\n }\n\n private resize(): void {\n this._buckets = new Array(this._buckets.length * 2).fill(null);\n // Rebuild the bucket chains (`next`) from the order list (`after`)\n for (let node = this._head; node !== null; node = node.after) {\n const index = this.getBucketIndex(node.hash);\n node.next = this._buckets[index] ?? null;\n this._buckets[index] = node;\n }\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n toString(): string {\n const entries = Array.from(this.entries())\n .map(({ key, value }) => `${key}=${value}`)\n .join(', ');\n return `LinkedHashMap{${entries}}`;\n }\n}\n\n/**\n * Factory function to make a LinkedHashMap.\n *\n * @example\n * const map = linkedHashMap<string, number>()\n * map.set('a', 1)\n * map.set('b', 2)\n *\n * @example\n * // With initial entries\n * const map = linkedHashMap<string, number>([\n * ['a', 1],\n * ['b', 2]\n * ])\n *\n * @example\n * // LRU cache with access order\n * const lru = linkedHashMap<string, number>({ accessOrder: true })\n */\nexport function linkedHashMap<K, V>(\n optionsOrEntries?: LinkedHashMapOptions<K, V> | Iterable<[K, V]>\n): LinkedHashMap<K, V> {\n if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {\n const map = new LinkedHashMap<K, V>();\n for (const [key, value] of optionsOrEntries as Iterable<[K, V]>) {\n map.set(key, value);\n }\n return map;\n }\n\n return new LinkedHashMap<K, V>(optionsOrEntries as LinkedHashMapOptions<K, V>);\n}\n","/**\n * TreeMap - Red-black tree based sorted map implementation.\n *\n * This module implements a self-balancing binary search tree that maintains keys in sorted\n * order. Mirrors java.util.TreeMap.\n *\n * Key features:\n * - O(log n) access, insert, delete\n * - Keys maintained in sorted order (natural or custom comparator)\n * - Navigation methods (floor, ceiling, lower, higher)\n * - Range view operations (subMap, headMap, tailMap)\n *\n * @example\n * const map = treeMap<string, number>()\n * map.set('c', 3)\n * map.set('a', 1)\n * map.set('b', 2)\n * // Iteration order: a, b, c (sorted)\n *\n * @example\n * // Custom comparator for descending order\n * const map = treeMap<number, string>({\n * compare: (a, b) => b - a\n * })\n */\n\nimport type { NavigableMap, SortedMap, Entry } from \"../interfaces/map.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Node color in red-black tree.\n */\nconst Color = {\n RED: \"RED\",\n BLACK: \"BLACK\",\n} as const;\ntype Color = (typeof Color)[keyof typeof Color];\n\n/**\n * Node in the red-black tree.\n */\ninterface TreeNode<K, V> {\n key: K;\n value: V;\n color: Color;\n left: TreeNode<K, V> | null;\n right: TreeNode<K, V> | null;\n parent: TreeNode<K, V> | null;\n}\n\n// Null-safe helpers of the red-black algorithms: a null leaf is black\nfunction colorOf<K, V>(node: TreeNode<K, V> | null): Color {\n return node === null ? Color.BLACK : node.color;\n}\nfunction parentOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {\n return node === null ? null : node.parent;\n}\nfunction leftOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {\n return node === null ? null : node.left;\n}\nfunction rightOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {\n return node === null ? null : node.right;\n}\nfunction setColor<K, V>(node: TreeNode<K, V> | null, color: Color): void {\n if (node !== null) node.color = color;\n}\n\n/**\n * Options for making a TreeMap.\n */\nexport interface TreeMapOptions<K, V> {\n /**\n * Comparison function for keys.\n * @default defaultCompare\n */\n compare?: Compare<K>;\n\n /**\n * Equality function for keys.\n * @default defaultEq\n */\n eq?: Eq<K>;\n\n /**\n * Equality function for values.\n * @default defaultEq\n */\n valueEq?: Eq<V>;\n}\n\n/**\n * TreeMap<K, V> - Red-black tree based sorted map.\n *\n * Maintains keys in sorted order using a self-balancing binary search tree.\n * This class gives O(log n) operations and navigation methods.\n */\nexport class TreeMap<K, V> implements NavigableMap<K, V> {\n private _root: TreeNode<K, V> | null = null;\n private _size: number = 0;\n private readonly _compare: Compare<K>;\n private readonly _eq: Eq<K>;\n private readonly _valueEq: Eq<V>;\n\n constructor(options: TreeMapOptions<K, V> = {}) {\n const {\n compare = defaultCompare,\n eq = defaultEq,\n valueEq = defaultEq,\n } = options;\n\n this._compare = compare;\n this._eq = eq;\n this._valueEq = valueEq;\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get comparator(): Compare<K> {\n return this._compare;\n }\n\n get keyEq(): Eq<K> {\n return this._eq;\n }\n\n get valueEq(): Eq<V> {\n return this._valueEq;\n }\n\n // ========================================================================\n // Lookup operations\n // ========================================================================\n\n has(key: K): boolean {\n return this.getNode(key) !== null;\n }\n\n containsKey(key: K): boolean {\n return this.has(key);\n }\n\n containsValue(value: V): boolean {\n return this.findValue(this._root, value);\n }\n\n get(key: K): V {\n const node = this.getNode(key);\n if (node === null) {\n throw new Error(\"Key not found\");\n }\n return node.value;\n }\n\n getOrUndefined(key: K): V | undefined {\n const node = this.getNode(key);\n return node?.value;\n }\n\n getOrDefault(key: K, defaultValue: V): V {\n const node = this.getNode(key);\n return node !== null ? node.value : defaultValue;\n }\n\n // ========================================================================\n // Modification operations\n // ========================================================================\n\n set(key: K, value: V): V | undefined {\n if (this._root === null) {\n this._root = this.createNode(key, value, Color.BLACK);\n this._size++;\n return undefined;\n }\n\n // Find insertion point\n let node: TreeNode<K, V> | null = this._root;\n let parent: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n parent = node;\n const cmp = this._compare(key, node.key);\n\n if (cmp === 0) {\n // Key exists, replace value\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n node = node.right;\n }\n }\n\n // Insert new node\n const newNode = this.createNode(key, value, Color.RED);\n newNode.parent = parent;\n\n if (parent !== null) {\n const cmp = this._compare(key, parent.key);\n if (cmp < 0) {\n parent.left = newNode;\n } else {\n parent.right = newNode;\n }\n }\n\n this._size++;\n this.fixAfterInsertion(newNode);\n return undefined;\n }\n\n setIfAbsent(key: K, value: V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n return existing.value;\n }\n this.set(key, value);\n return value;\n }\n\n replace(key: K, value: V): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n const oldValue = node.value;\n node.value = value;\n return oldValue;\n }\n\n replaceEntry(key: K, oldValue: V, newValue: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, oldValue)) {\n return false;\n }\n node.value = newValue;\n return true;\n }\n\n delete(key: K): V | undefined {\n const node = this.getNode(key);\n if (node === null) return undefined;\n\n const oldValue = node.value;\n this.deleteNode(node);\n this._size--;\n return oldValue;\n }\n\n deleteEntry(key: K, value: V): boolean {\n const node = this.getNode(key);\n if (node === null || !this._valueEq(node.value, value)) {\n return false;\n }\n this.deleteNode(node);\n this._size--;\n return true;\n }\n\n clear(): void {\n this._root = null;\n this._size = 0;\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n putAll(other: NavigableMap<K, V> | Iterable<Entry<K, V>>): void {\n if ('entries' in other && typeof other.entries === 'function') {\n for (const entry of other.entries()) {\n this.set(entry.key, entry.value);\n }\n } else {\n for (const entry of other as Iterable<Entry<K, V>>) {\n this.set(entry.key, entry.value);\n }\n }\n }\n\n // ========================================================================\n // Computed operations\n // ========================================================================\n\n computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {\n const existing = this.getNode(key);\n if (existing !== null) {\n return existing.value;\n }\n const value = mappingFunction(key);\n this.set(key, value);\n return value;\n }\n\n computeIfPresent(key: K, remappingFunction: (key: K, value: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n if (existing === null) return undefined;\n\n const newValue = remappingFunction(key, existing.value);\n if (newValue === undefined) {\n this.delete(key);\n return undefined;\n }\n existing.value = newValue;\n return newValue;\n }\n\n compute(key: K, remappingFunction: (key: K, value: V | undefined) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n const newValue = remappingFunction(key, existing?.value);\n\n if (newValue === undefined) {\n if (existing !== null) {\n this.delete(key);\n }\n return undefined;\n }\n\n this.set(key, newValue);\n return newValue;\n }\n\n merge(key: K, value: V, remappingFunction: (oldValue: V, newValue: V) => V | undefined): V | undefined {\n const existing = this.getNode(key);\n\n if (existing === null) {\n this.set(key, value);\n return value;\n }\n\n const merged = remappingFunction(existing.value, value);\n if (merged === undefined) {\n this.delete(key);\n return undefined;\n }\n\n existing.value = merged;\n return merged;\n }\n\n // ========================================================================\n // SortedMap operations\n // ========================================================================\n\n firstKey(): K {\n if (this._root === null) {\n throw new Error(\"Map is empty\");\n }\n return this.getFirstNode(this._root).key;\n }\n\n lastKey(): K {\n if (this._root === null) {\n throw new Error(\"Map is empty\");\n }\n return this.getLastNode(this._root).key;\n }\n\n headMap(toKey: K): SortedMap<K, V> {\n // Return a view (simplified: create new map with filtered entries)\n const result = new TreeMap<K, V>({\n compare: this._compare,\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n for (const entry of this.entries()) {\n if (this._compare(entry.key, toKey) < 0) {\n result.set(entry.key, entry.value);\n } else {\n break; // Keys are sorted, so we can stop\n }\n }\n\n return result;\n }\n\n tailMap(fromKey: K): SortedMap<K, V> {\n const result = new TreeMap<K, V>({\n compare: this._compare,\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n let started = false;\n for (const entry of this.entries()) {\n if (!started && this._compare(entry.key, fromKey) < 0) {\n continue;\n }\n started = true;\n result.set(entry.key, entry.value);\n }\n\n return result;\n }\n\n subMap(fromKey: K, toKey: K): SortedMap<K, V> {\n const result = new TreeMap<K, V>({\n compare: this._compare,\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n for (const entry of this.entries()) {\n const cmpFrom = this._compare(entry.key, fromKey);\n const cmpTo = this._compare(entry.key, toKey);\n\n if (cmpFrom >= 0 && cmpTo < 0) {\n result.set(entry.key, entry.value);\n } else if (cmpTo >= 0) {\n break; // Past the range\n }\n }\n\n return result;\n }\n\n // ========================================================================\n // NavigableMap operations\n // ========================================================================\n\n floorKey(key: K): K | undefined {\n return this.floorEntry(key)?.key;\n }\n\n ceilingKey(key: K): K | undefined {\n return this.ceilingEntry(key)?.key;\n }\n\n lowerKey(key: K): K | undefined {\n return this.lowerEntry(key)?.key;\n }\n\n higherKey(key: K): K | undefined {\n return this.higherEntry(key)?.key;\n }\n\n floorEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp === 0) {\n return { key: node.key, value: node.value };\n } else if (cmp < 0) {\n node = node.left;\n } else {\n result = node; // This node is <= key\n node = node.right;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n ceilingEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp === 0) {\n return { key: node.key, value: node.value };\n } else if (cmp > 0) {\n node = node.right;\n } else {\n result = node; // This node is >= key\n node = node.left;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n lowerEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp <= 0) {\n node = node.left;\n } else {\n result = node; // This node is < key\n node = node.right;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n higherEntry(key: K): Entry<K, V> | undefined {\n let node = this._root;\n let result: TreeNode<K, V> | null = null;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp >= 0) {\n node = node.right;\n } else {\n result = node; // This node is > key\n node = node.left;\n }\n }\n\n return result ? { key: result.key, value: result.value } : undefined;\n }\n\n firstEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getFirstNode(this._root);\n return { key: node.key, value: node.value };\n }\n\n lastEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getLastNode(this._root);\n return { key: node.key, value: node.value };\n }\n\n pollFirstEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getFirstNode(this._root);\n const entry = { key: node.key, value: node.value };\n this.deleteNode(node);\n this._size--;\n return entry;\n }\n\n pollLastEntry(): Entry<K, V> | undefined {\n if (this._root === null) return undefined;\n const node = this.getLastNode(this._root);\n const entry = { key: node.key, value: node.value };\n this.deleteNode(node);\n this._size--;\n return entry;\n }\n\n descendingMap(): NavigableMap<K, V> {\n // Create a new TreeMap with reversed comparator\n const reversed = new TreeMap<K, V>({\n compare: (a, b) => this._compare(b, a),\n eq: this._eq,\n valueEq: this._valueEq,\n });\n\n for (const entry of this.entries()) {\n reversed.set(entry.key, entry.value);\n }\n\n return reversed;\n }\n\n *descendingKeys(): IterableIterator<K> {\n yield* this.reverseInOrderTraversal(this._root, (node) => node.key);\n }\n\n // ========================================================================\n // View operations\n // ========================================================================\n\n *keys(): IterableIterator<K> {\n yield* this.inOrderTraversal(this._root, (node) => node.key);\n }\n\n *values(): IterableIterator<V> {\n yield* this.inOrderTraversal(this._root, (node) => node.value);\n }\n\n *entries(): IterableIterator<Entry<K, V>> {\n yield* this.inOrderTraversal(this._root, (node) => ({\n key: node.key,\n value: node.value,\n }));\n }\n\n *[Symbol.iterator](): Iterator<Entry<K, V>> {\n yield* this.entries();\n }\n\n forEach(action: (value: V, key: K, map: this) => void): void {\n for (const entry of this.entries()) {\n action(entry.value, entry.key, this);\n }\n }\n\n toArray(): Entry<K, V>[] {\n return Array.from(this.entries());\n }\n\n // ========================================================================\n // Private helpers - Tree operations\n // ========================================================================\n\n private createNode(key: K, value: V, color: Color): TreeNode<K, V> {\n return {\n key,\n value,\n color,\n left: null,\n right: null,\n parent: null,\n };\n }\n\n private getNode(key: K): TreeNode<K, V> | null {\n let node = this._root;\n\n while (node !== null) {\n const cmp = this._compare(key, node.key);\n if (cmp === 0) {\n return node;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n node = node.right;\n }\n }\n\n return null;\n }\n\n private getFirstNode(node: TreeNode<K, V>): TreeNode<K, V> {\n while (node.left !== null) {\n node = node.left;\n }\n return node;\n }\n\n private getLastNode(node: TreeNode<K, V>): TreeNode<K, V> {\n while (node.right !== null) {\n node = node.right;\n }\n return node;\n }\n\n private findValue(node: TreeNode<K, V> | null, value: V): boolean {\n if (node === null) return false;\n if (this._valueEq(node.value, value)) return true;\n return this.findValue(node.left, value) || this.findValue(node.right, value);\n }\n\n private *inOrderTraversal<T>(\n node: TreeNode<K, V> | null,\n mapper: (node: TreeNode<K, V>) => T\n ): IterableIterator<T> {\n if (node === null) return;\n yield* this.inOrderTraversal(node.left, mapper);\n yield mapper(node);\n yield* this.inOrderTraversal(node.right, mapper);\n }\n\n private *reverseInOrderTraversal<T>(\n node: TreeNode<K, V> | null,\n mapper: (node: TreeNode<K, V>) => T\n ): IterableIterator<T> {\n if (node === null) return;\n yield* this.reverseInOrderTraversal(node.right, mapper);\n yield mapper(node);\n yield* this.reverseInOrderTraversal(node.left, mapper);\n }\n\n // ========================================================================\n // Private helpers - Red-black tree balancing\n // ========================================================================\n\n private rotateLeft(node: TreeNode<K, V> | null): void {\n if (node === null || node.right === null) return;\n const right = node.right;\n node.right = right.left;\n\n if (right.left !== null) {\n right.left.parent = node;\n }\n\n right.parent = node.parent;\n\n if (node.parent === null) {\n this._root = right;\n } else if (node === node.parent.left) {\n node.parent.left = right;\n } else {\n node.parent.right = right;\n }\n\n right.left = node;\n node.parent = right;\n }\n\n private rotateRight(node: TreeNode<K, V> | null): void {\n if (node === null || node.left === null) return;\n const left = node.left;\n node.left = left.right;\n\n if (left.right !== null) {\n left.right.parent = node;\n }\n\n left.parent = node.parent;\n\n if (node.parent === null) {\n this._root = left;\n } else if (node === node.parent.right) {\n node.parent.right = left;\n } else {\n node.parent.left = left;\n }\n\n left.right = node;\n node.parent = left;\n }\n\n private fixAfterInsertion(node: TreeNode<K, V>): void {\n while (node.parent !== null && node.parent.color === Color.RED) {\n if (node.parent === node.parent.parent?.left) {\n const uncle = node.parent.parent.right;\n\n if (uncle?.color === Color.RED) {\n // Case 1: Uncle is red\n node.parent.color = Color.BLACK;\n uncle.color = Color.BLACK;\n node.parent.parent.color = Color.RED;\n node = node.parent.parent;\n } else {\n if (node === node.parent.right) {\n // Case 2: Node is right child\n node = node.parent;\n this.rotateLeft(node);\n }\n // Case 3: Node is left child\n node.parent!.color = Color.BLACK;\n node.parent!.parent!.color = Color.RED;\n this.rotateRight(node.parent!.parent!);\n }\n } else {\n const uncle = node.parent.parent?.left ?? null;\n\n if (uncle?.color === Color.RED) {\n // Case 1: Uncle is red\n node.parent.color = Color.BLACK;\n uncle.color = Color.BLACK;\n node.parent.parent!.color = Color.RED;\n node = node.parent.parent!;\n } else {\n if (node === node.parent.left) {\n // Case 2: Node is left child\n node = node.parent;\n this.rotateRight(node);\n }\n // Case 3: Node is right child\n node.parent!.color = Color.BLACK;\n node.parent!.parent!.color = Color.RED;\n this.rotateLeft(node.parent!.parent!);\n }\n }\n }\n\n this._root!.color = Color.BLACK;\n }\n\n /**\n * This method deletes a node (the CLRS algorithm, as in java.util.TreeMap). A null leaf counts as black.\n *\n * Before (BUGS-2026-07 L10): the deletion of a black leaf skipped the fix-up, so the black\n * heights drifted and the tree became unbalanced. Also, the fix-up treated a null leaf as\n * \"not black\", so it chose the wrong case and rotated at null (a TypeError).\n */\n private deleteNode(target: TreeNode<K, V>): void {\n let node = target;\n // A node with two children takes the key and value of its successor, then the successor goes\n if (node.left !== null && node.right !== null) {\n const successor = this.getFirstNode(node.right);\n node.key = successor.key;\n node.value = successor.value;\n node = successor;\n }\n\n const replacement = node.left ?? node.right;\n if (replacement !== null) {\n replacement.parent = node.parent;\n if (node.parent === null) this._root = replacement;\n else if (node === node.parent.left) node.parent.left = replacement;\n else node.parent.right = replacement;\n node.left = node.right = node.parent = null;\n if (node.color === Color.BLACK) this.fixAfterDeletion(replacement);\n } else if (node.parent === null) {\n // The only node\n this._root = null;\n } else {\n // A leaf: it is its own phantom replacement during the fix-up, then it goes\n if (node.color === Color.BLACK) this.fixAfterDeletion(node);\n if (node.parent !== null) {\n if (node === node.parent.left) node.parent.left = null;\n else if (node === node.parent.right) node.parent.right = null;\n node.parent = null;\n }\n }\n }\n\n private fixAfterDeletion(start: TreeNode<K, V>): void {\n let x: TreeNode<K, V> | null = start;\n while (x !== this._root && colorOf(x) === Color.BLACK) {\n if (x === leftOf(parentOf(x))) {\n let sibling = rightOf(parentOf(x));\n if (colorOf(sibling) === Color.RED) {\n setColor(sibling, Color.BLACK);\n setColor(parentOf(x), Color.RED);\n this.rotateLeft(parentOf(x));\n sibling = rightOf(parentOf(x));\n }\n if (colorOf(leftOf(sibling)) === Color.BLACK && colorOf(rightOf(sibling)) === Color.BLACK) {\n setColor(sibling, Color.RED);\n x = parentOf(x);\n } else {\n if (colorOf(rightOf(sibling)) === Color.BLACK) {\n setColor(leftOf(sibling), Color.BLACK);\n setColor(sibling, Color.RED);\n this.rotateRight(sibling);\n sibling = rightOf(parentOf(x));\n }\n setColor(sibling, colorOf(parentOf(x)));\n setColor(parentOf(x), Color.BLACK);\n setColor(rightOf(sibling), Color.BLACK);\n this.rotateLeft(parentOf(x));\n x = this._root;\n }\n } else {\n let sibling = leftOf(parentOf(x));\n if (colorOf(sibling) === Color.RED) {\n setColor(sibling, Color.BLACK);\n setColor(parentOf(x), Color.RED);\n this.rotateRight(parentOf(x));\n sibling = leftOf(parentOf(x));\n }\n if (colorOf(rightOf(sibling)) === Color.BLACK && colorOf(leftOf(sibling)) === Color.BLACK) {\n setColor(sibling, Color.RED);\n x = parentOf(x);\n } else {\n if (colorOf(leftOf(sibling)) === Color.BLACK) {\n setColor(rightOf(sibling), Color.BLACK);\n setColor(sibling, Color.RED);\n this.rotateLeft(sibling);\n sibling = leftOf(parentOf(x));\n }\n setColor(sibling, colorOf(parentOf(x)));\n setColor(parentOf(x), Color.BLACK);\n setColor(leftOf(sibling), Color.BLACK);\n this.rotateRight(parentOf(x));\n x = this._root;\n }\n }\n }\n setColor(x, Color.BLACK);\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n toString(): string {\n const entries = Array.from(this.entries())\n .map(({ key, value }) => `${key}=${value}`)\n .join(', ');\n return `TreeMap{${entries}}`;\n }\n}\n\n/**\n * Factory function to make a TreeMap.\n *\n * @example\n * const map = treeMap<string, number>()\n * map.set('c', 3)\n * map.set('a', 1)\n * map.set('b', 2)\n * // Iteration order: a, b, c\n *\n * @example\n * // With initial entries\n * const map = treeMap<string, number>([\n * ['c', 3],\n * ['a', 1],\n * ['b', 2]\n * ])\n *\n * @example\n * // Custom comparator for descending order\n * const map = treeMap<number, string>({ compare: (a, b) => b - a })\n */\nexport function treeMap<K, V>(\n optionsOrEntries?: TreeMapOptions<K, V> | Iterable<[K, V]>\n): TreeMap<K, V> {\n if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {\n const map = new TreeMap<K, V>();\n for (const [key, value] of optionsOrEntries as Iterable<[K, V]>) {\n map.set(key, value);\n }\n return map;\n }\n\n return new TreeMap<K, V>(optionsOrEntries as TreeMapOptions<K, V>);\n}\n","/**\n * TreeSet - Red-black tree based sorted set implementation.\n *\n * This module implements a sorted set using TreeMap as the backing structure.\n * Mirrors java.util.TreeSet.\n *\n * Key features:\n * - O(log n) add, remove, contains\n * - Elements maintained in sorted order (natural or custom comparator)\n * - Navigation methods (floor, ceiling, lower, higher)\n * - Range view operations (subSet, headSet, tailSet)\n *\n * @example\n * const set = treeSet<string>()\n * set.add('c')\n * set.add('a')\n * set.add('b')\n * // Iteration order: a, b, c (sorted)\n *\n * @example\n * // Custom comparator for descending order\n * const set = treeSet<number>({\n * compare: (a, b) => b - a\n * })\n */\n\nimport type { SortedSet, NavigableSet } from \"../interfaces/set.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { TreeMap } from \"./tree-map.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Dummy value used for TreeMap backing.\n */\nconst PRESENT = true;\n\n/**\n * Options for making a TreeSet.\n */\nexport interface TreeSetOptions<T> {\n /**\n * Comparison function for elements.\n * @default defaultCompare\n */\n compare?: Compare<T>;\n\n /**\n * Equality function for elements.\n * @default defaultEq\n */\n eq?: Eq<T>;\n}\n\n/**\n * TreeSet<T> - Red-black tree based sorted set.\n *\n * Maintains elements in sorted order using a TreeMap as backing structure.\n * This class gives O(log n) operations and navigation methods.\n */\nexport class TreeSet<T> implements NavigableSet<T> {\n private readonly _map: TreeMap<T, boolean>;\n private readonly _compare: Compare<T>;\n private readonly _eq: Eq<T>;\n\n constructor(options: TreeSetOptions<T> = {}) {\n const {\n compare = defaultCompare,\n eq = defaultEq,\n } = options;\n\n this._compare = compare;\n this._eq = eq;\n this._map = new TreeMap<T, boolean>({\n compare,\n eq,\n });\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this._map.size;\n }\n\n get isEmpty(): boolean {\n return this._map.isEmpty;\n }\n\n get comparator(): Compare<T> {\n return this._compare;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Membership operations\n // ========================================================================\n\n has(element: T): boolean {\n return this._map.has(element);\n }\n\n contains(element: T): boolean {\n return this.has(element);\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n // ========================================================================\n // Modification operations\n // ========================================================================\n\n add(element: T): boolean {\n const oldValue = this._map.set(element, PRESENT);\n return oldValue === undefined; // Returns true if element was added (not already present)\n }\n\n remove(element: T): boolean {\n const removed = this._map.delete(element);\n return removed !== undefined;\n }\n\n clear(): void {\n this._map.clear();\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n addAll(elements: Iterable<T>): boolean {\n let modified = false;\n for (const element of elements) {\n if (this.add(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n removeAll(elements: Iterable<T>): boolean {\n let modified = false;\n for (const element of elements) {\n if (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(elements: Iterable<T>): boolean {\n const toRetain = this.setOf(elements);\n\n let modified = false;\n for (const element of Array.from(this)) {\n if (!toRetain.has(element)) {\n this.remove(element);\n modified = true;\n }\n }\n return modified;\n }\n\n // ========================================================================\n // Set operations\n // ========================================================================\n\n union(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n for (const element of this) {\n result.add(element);\n }\n for (const element of other) {\n result.add(element);\n }\n\n return result;\n }\n\n intersection(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (otherSet.has(element)) {\n result.add(element);\n }\n }\n\n return result;\n }\n\n difference(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (!otherSet.has(element)) {\n result.add(element);\n }\n }\n\n return result;\n }\n\n symmetricDifference(other: Iterable<T>): TreeSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n // Add all elements from this set\n for (const element of this) {\n result.add(element);\n }\n\n // Toggle each element of the other set one time, so a repeated element does not toggle back\n for (const element of this.setOf(other)) {\n if (result.has(element)) {\n result.remove(element);\n } else {\n result.add(element);\n }\n }\n\n return result;\n }\n\n isSubsetOf(other: Iterable<T>): boolean {\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (!otherSet.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * This method makes a set of the elements, with the comparator and the equality of this set.\n * Before, the set operations used a native `Set`, which compares with `===` and ignores the comparator.\n */\n private setOf(elements: Iterable<T>): TreeSet<T> {\n const set = new TreeSet<T>({ compare: this._compare, eq: this._eq });\n for (const element of elements) {\n set.add(element);\n }\n return set;\n }\n\n isSupersetOf(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n isDisjointFrom(other: Iterable<T>): boolean {\n for (const element of other) {\n if (this.has(element)) {\n return false;\n }\n }\n return true;\n }\n\n // ========================================================================\n // SortedSet operations\n // ========================================================================\n\n first(): T {\n const key = this._map.firstKey();\n return key;\n }\n\n last(): T {\n const key = this._map.lastKey();\n return key;\n }\n\n headSet(toElement: T): SortedSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n for (const element of this) {\n if (this._compare(element, toElement) < 0) {\n result.add(element);\n } else {\n break; // Elements are sorted\n }\n }\n\n return result;\n }\n\n tailSet(fromElement: T): SortedSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n let started = false;\n for (const element of this) {\n if (!started && this._compare(element, fromElement) < 0) {\n continue;\n }\n started = true;\n result.add(element);\n }\n\n return result;\n }\n\n subSet(fromElement: T, toElement: T): SortedSet<T> {\n const result = new TreeSet<T>({\n compare: this._compare,\n eq: this._eq,\n });\n\n for (const element of this) {\n const cmpFrom = this._compare(element, fromElement);\n const cmpTo = this._compare(element, toElement);\n\n if (cmpFrom >= 0 && cmpTo < 0) {\n result.add(element);\n } else if (cmpTo >= 0) {\n break; // Past the range\n }\n }\n\n return result;\n }\n\n // ========================================================================\n // NavigableSet operations\n // ========================================================================\n\n floor(element: T): T | undefined {\n return this._map.floorKey(element);\n }\n\n ceiling(element: T): T | undefined {\n return this._map.ceilingKey(element);\n }\n\n lower(element: T): T | undefined {\n return this._map.lowerKey(element);\n }\n\n higher(element: T): T | undefined {\n return this._map.higherKey(element);\n }\n\n pollFirst(): T | undefined {\n const entry = this._map.pollFirstEntry();\n return entry?.key;\n }\n\n pollLast(): T | undefined {\n const entry = this._map.pollLastEntry();\n return entry?.key;\n }\n\n descendingSet(): NavigableSet<T> {\n const reversed = new TreeSet<T>({\n compare: (a, b) => this._compare(b, a),\n eq: this._eq,\n });\n\n for (const element of this) {\n reversed.add(element);\n }\n\n return reversed;\n }\n\n *descendingIterator(): IterableIterator<T> {\n yield* this._map.descendingKeys();\n }\n\n // ========================================================================\n // View operations\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n yield* this._map.keys();\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let index = 0;\n for (const element of this) {\n action(element, index++);\n }\n }\n\n toArray(): T[] {\n return Array.from(this);\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n toString(): string {\n const elements = Array.from(this).join(', ');\n return `TreeSet{${elements}}`;\n }\n}\n\n/**\n * Factory function to make a TreeSet.\n *\n * @example\n * const set = treeSet<string>()\n * set.add('c')\n * set.add('a')\n * set.add('b')\n * // Iteration order: a, b, c\n *\n * @example\n * // With initial elements\n * const set = treeSet(['c', 'a', 'b'])\n * // Iteration order: a, b, c\n *\n * @example\n * // Custom comparator for descending order\n * const set = treeSet<number>({ compare: (a, b) => b - a })\n */\nexport function treeSet<T>(\n optionsOrElements?: TreeSetOptions<T> | Iterable<T>\n): TreeSet<T> {\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const set = new TreeSet<T>();\n for (const element of optionsOrElements as Iterable<T>) {\n set.add(element);\n }\n return set;\n }\n\n return new TreeSet<T>(optionsOrElements as TreeSetOptions<T>);\n}\n","/**\n * LinkedList implementation - A doubly-linked list.\n *\n * This module gives O(1) insertion/removal at both ends and at known positions.\n * Slower random access O(n) compared to ArrayList.\n * Mirrors java.util.LinkedList.\n *\n * @example\n * const list = linkedList<number>()\n * list.addFirst(1)\n * list.addLast(2)\n * list.add(3)\n */\n\nimport type { List } from \"../interfaces/list.js\";\nimport type { Deque } from \"../interfaces/queue.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Internal node structure for the linked list.\n */\nclass Node<T> {\n value: T;\n prev: Node<T> | null;\n next: Node<T> | null;\n\n constructor(value: T, prev: Node<T> | null = null, next: Node<T> | null = null) {\n this.value = value;\n this.prev = prev;\n this.next = next;\n }\n}\n\n/**\n * Options for making a LinkedList.\n */\nexport interface LinkedListOptions<T> {\n /**\n * Equality function for comparing elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n}\n\n/**\n * LinkedList<T> - Doubly-linked list implementation.\n *\n * Efficient for:\n * - Insertion/removal at ends: O(1)\n * - Insertion/removal at known position: O(1)\n * - Sequential iteration: O(n)\n *\n * Not efficient for:\n * - Random access by index: O(n)\n * - Search: O(n)\n *\n * This class implements both List and Deque interfaces.\n */\nexport class LinkedList<T> implements List<T>, Deque<T> {\n private _head: Node<T> | null = null;\n private _tail: Node<T> | null = null;\n private _size: number = 0;\n private readonly _eq: Eq<T>;\n\n constructor(options: LinkedListOptions<T> = {}) {\n const { eq = defaultEq } = options;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._size;\n }\n\n get isEmpty(): boolean {\n return this._size === 0;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Deque operations (both ends)\n // ========================================================================\n\n addFirst(element: T): void {\n const newNode = new Node(element, null, this._head);\n if (this._head) {\n this._head.prev = newNode;\n }\n this._head = newNode;\n if (!this._tail) {\n this._tail = newNode;\n }\n this._size++;\n }\n\n addLast(element: T): void {\n const newNode = new Node(element, this._tail, null);\n if (this._tail) {\n this._tail.next = newNode;\n }\n this._tail = newNode;\n if (!this._head) {\n this._head = newNode;\n }\n this._size++;\n }\n\n removeFirst(): T {\n if (!this._head) {\n throw new Error(\"List is empty\");\n }\n return this.pollFirst()!;\n }\n\n removeLast(): T {\n if (!this._tail) {\n throw new Error(\"List is empty\");\n }\n return this.pollLast()!;\n }\n\n pollFirst(): T | undefined {\n if (!this._head) return undefined;\n\n const value = this._head.value;\n this._head = this._head.next;\n\n if (this._head) {\n this._head.prev = null;\n } else {\n this._tail = null;\n }\n\n this._size--;\n return value;\n }\n\n pollLast(): T | undefined {\n if (!this._tail) return undefined;\n\n const value = this._tail.value;\n this._tail = this._tail.prev;\n\n if (this._tail) {\n this._tail.next = null;\n } else {\n this._head = null;\n }\n\n this._size--;\n return value;\n }\n\n peekFirst(): T {\n if (!this._head) {\n throw new Error(\"List is empty\");\n }\n return this._head.value;\n }\n\n peekLast(): T {\n if (!this._tail) {\n throw new Error(\"List is empty\");\n }\n return this._tail.value;\n }\n\n peekFirstOrUndefined(): T | undefined {\n return this._head?.value;\n }\n\n peekLastOrUndefined(): T | undefined {\n return this._tail?.value;\n }\n\n offerFirst(element: T): boolean {\n this.addFirst(element);\n return true;\n }\n\n offerLast(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n // ========================================================================\n // Stack operations (LIFO at the end, as on a JavaScript array)\n // ========================================================================\n\n // push and pop work at the end, and shift/unshift at the front, in every collection of this\n // package. Before, they worked at the front here (the Java Deque rule), so a LinkedList used\n // as a List reversed the pushed elements (ARCHITECTURE-PROPOSALS P8).\n push(element: T): void {\n this.addLast(element);\n }\n\n pop(): T {\n return this.removeLast();\n }\n\n // ========================================================================\n // Queue operations (FIFO)\n // ========================================================================\n\n offer(element: T): boolean {\n return this.offerLast(element);\n }\n\n poll(): T {\n return this.removeFirst();\n }\n\n peek(): T {\n return this.peekFirst();\n }\n\n peekOrUndefined(): T | undefined {\n return this.peekFirstOrUndefined();\n }\n\n pollOrUndefined(): T | undefined {\n return this.pollFirst();\n }\n\n enqueue(element: T): boolean {\n return this.offer(element);\n }\n\n dequeue(): T {\n return this.poll();\n }\n\n // ========================================================================\n // List operations\n // ========================================================================\n\n get(index: number): T {\n const node = this.getNode(index);\n return node.value;\n }\n\n set(index: number, element: T): T {\n const node = this.getNode(index);\n const old = node.value;\n node.value = element;\n return old;\n }\n\n insert(index: number, element: T): void {\n if (index < 0 || index > this._size) {\n throw new RangeError(`Index ${index} out of bounds for size ${this._size}`);\n }\n\n if (index === 0) {\n this.addFirst(element);\n return;\n }\n\n if (index === this._size) {\n this.addLast(element);\n return;\n }\n\n const nextNode = this.getNode(index);\n const prevNode = nextNode.prev!;\n const newNode = new Node(element, prevNode, nextNode);\n\n prevNode.next = newNode;\n nextNode.prev = newNode;\n this._size++;\n }\n\n insertAll(index: number, other: Iterable<T>): boolean {\n if (index < 0 || index > this._size) {\n throw new RangeError(`Index ${index} out of bounds for size ${this._size}`);\n }\n\n const elements = Array.from(other);\n if (elements.length === 0) return false;\n\n for (let i = 0; i < elements.length; i++) {\n this.insert(index + i, elements[i]!);\n }\n\n return true;\n }\n\n removeAt(index: number): T {\n const node = this.getNode(index);\n return this.unlinkNode(node);\n }\n\n removeRange(fromIndex: number, toIndex: number): void {\n if (fromIndex < 0 || toIndex > this._size || fromIndex > toIndex) {\n throw new RangeError(`Invalid range [${fromIndex}, ${toIndex})`);\n }\n\n for (let i = fromIndex; i < toIndex; i++) {\n this.removeAt(fromIndex);\n }\n }\n\n indexOf(element: T, fromIndex: number = 0): number {\n let index = 0;\n let node = this._head;\n\n while (node) {\n if (index >= fromIndex && this._eq(node.value, element)) {\n return index;\n }\n node = node.next;\n index++;\n }\n\n return -1;\n }\n\n lastIndexOf(element: T, fromIndex?: number): number {\n const start = fromIndex !== undefined ? fromIndex : this._size - 1;\n let index = this._size - 1;\n let node = this._tail;\n\n while (node && index >= 0) {\n if (index <= start && this._eq(node.value, element)) {\n return index;\n }\n node = node.prev;\n index--;\n }\n\n return -1;\n }\n\n first(): T {\n return this.peekFirst();\n }\n\n last(): T {\n return this.peekLast();\n }\n\n shift(): T {\n return this.removeFirst();\n }\n\n unshift(element: T): void {\n this.addFirst(element);\n }\n\n // ========================================================================\n // Collection operations\n // ========================================================================\n\n add(element: T): boolean {\n this.addLast(element);\n return true;\n }\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n this.addLast(element);\n modified = true;\n }\n return modified;\n }\n\n contains(element: T): boolean {\n return this.indexOf(element) !== -1;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) return false;\n }\n return true;\n }\n\n remove(element: T): boolean {\n let node = this._head;\n\n while (node) {\n if (this._eq(node.value, element)) {\n this.unlinkNode(node);\n return true;\n }\n node = node.next;\n }\n\n return false;\n }\n\n removeAll(other: Iterable<T>): boolean {\n const toRemove = new Set(other);\n let modified = false;\n\n for (const element of toRemove) {\n while (this.remove(element)) {\n modified = true;\n }\n }\n\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = new Set(other);\n let node = this._head;\n let modified = false;\n\n while (node) {\n const next = node.next;\n let shouldRetain = false;\n\n for (const retainElement of toRetain) {\n if (this._eq(node.value, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n\n if (!shouldRetain) {\n this.unlinkNode(node);\n modified = true;\n }\n\n node = next;\n }\n\n return modified;\n }\n\n clear(): void {\n this._head = null;\n this._tail = null;\n this._size = 0;\n }\n\n // ========================================================================\n // Sorting and reversing\n // ========================================================================\n\n sort(compare: Compare<T> = defaultCompare): void {\n if (this._size <= 1) return;\n\n // Convert to array, sort, rebuild list\n const array = this.toArray();\n array.sort(compare);\n\n this.clear();\n for (const element of array) {\n this.addLast(element);\n }\n }\n\n reverse(): void {\n if (this._size <= 1) return;\n\n let node = this._head;\n this._head = this._tail;\n this._tail = node;\n\n while (node) {\n const next = node.next;\n node.next = node.prev;\n node.prev = next;\n node = next;\n }\n }\n\n // ========================================================================\n // Views\n // ========================================================================\n\n subList(fromIndex: number, toIndex: number): List<T> {\n if (fromIndex < 0 || toIndex > this._size || fromIndex > toIndex) {\n throw new RangeError(`Invalid range [${fromIndex}, ${toIndex})`);\n }\n\n const sub = new LinkedList<T>({ eq: this._eq });\n let index = 0;\n let node = this._head;\n\n while (node && index < toIndex) {\n if (index >= fromIndex) {\n sub.addLast(node.value);\n }\n node = node.next;\n index++;\n }\n\n return sub;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n let node = this._head;\n while (node) {\n yield node.value;\n node = node.next;\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let index = 0;\n let node = this._head;\n\n while (node) {\n action(node.value, index);\n node = node.next;\n index++;\n }\n }\n\n toArray(): T[] {\n const result: T[] = [];\n let node = this._head;\n\n while (node) {\n result.push(node.value);\n node = node.next;\n }\n\n return result;\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n private getNode(index: number): Node<T> {\n if (index < 0 || index >= this._size) {\n throw new RangeError(`Index ${index} out of bounds for size ${this._size}`);\n }\n\n // Optimize: start from head or tail depending on index\n if (index < this._size / 2) {\n // Start from head\n let node = this._head!;\n for (let i = 0; i < index; i++) {\n node = node.next!;\n }\n return node;\n } else {\n // Start from tail\n let node = this._tail!;\n for (let i = this._size - 1; i > index; i--) {\n node = node.prev!;\n }\n return node;\n }\n }\n\n private unlinkNode(node: Node<T>): T {\n const value = node.value;\n\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this._head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this._tail = node.prev;\n }\n\n this._size--;\n return value;\n }\n\n // ========================================================================\n // Inspection\n // ========================================================================\n\n toString(): string {\n return `LinkedList[${this.toArray().join(\", \")}]`;\n }\n}\n\n/**\n * Factory function to make a LinkedList.\n *\n * @example\n * const list = linkedList<number>()\n * const listFromArray = linkedList([1, 2, 3])\n */\nexport function linkedList<T>(\n optionsOrElements?: LinkedListOptions<T> | Iterable<T>\n): LinkedList<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const list = new LinkedList<T>();\n list.addAll(optionsOrElements as Iterable<T>);\n return list;\n }\n\n return new LinkedList<T>(optionsOrElements as LinkedListOptions<T>);\n}\n","/**\n * HashSet implementation - A set backed by a HashMap.\n *\n * This module gives O(1) average case for add, remove, and contains operations.\n * Elements are unique based on custom equality and hash functions.\n * Mirrors java.util.HashSet.\n *\n * @example\n * const set = hashSet<number>()\n * set.add(1)\n * set.add(2)\n * set.add(1) // Returns false, already present\n * set.size // 2\n */\n\nimport type { Set } from \"../interfaces/set.js\";\nimport type { Eq, Hash } from \"../core/traits.js\";\nimport { HashMap } from \"./hash-map.js\";\nimport { defaultEq, defaultHash } from \"../utils/defaults.js\";\n\n/**\n * Dummy value used for the HashMap backing the set.\n */\nconst PRESENT = Symbol(\"PRESENT\");\n\n/**\n * Options for making a HashSet.\n */\nexport interface HashSetOptions<T> {\n /**\n * Initial capacity.\n * @default 16\n */\n initialCapacity?: number;\n\n /**\n * This option is the load factor threshold for a resize.\n * @default 0.75\n */\n loadFactor?: number;\n\n /**\n * Equality function for elements.\n * @default defaultEq (===)\n */\n eq?: Eq<T>;\n\n /**\n * Hash function for elements.\n * @default defaultHash\n */\n hash?: Hash<T>;\n}\n\n/**\n * HashSet<T> - Hash table implementation of the Set interface.\n *\n * A HashMap holds the elements. Its values are a dummy constant.\n * This class gives constant-time performance for basic operations.\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class HashSet<T> implements Set<T> {\n private readonly _map: HashMap<T, symbol>;\n private readonly _eq: Eq<T>;\n private readonly _hash: Hash<T>;\n\n constructor(options: HashSetOptions<T> = {}) {\n const {\n initialCapacity = 16,\n loadFactor = 0.75,\n eq = defaultEq,\n hash = defaultHash,\n } = options;\n\n this._eq = eq;\n this._hash = hash;\n this._map = new HashMap<T, symbol>({\n initialCapacity,\n loadFactor,\n keyEq: eq,\n keyHash: hash,\n });\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._map.size;\n }\n\n get isEmpty(): boolean {\n return this._map.isEmpty;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n // ========================================================================\n // Core set operations\n // ========================================================================\n\n add(element: T): boolean {\n const hadElement = this._map.has(element);\n this._map.set(element, PRESENT);\n return !hadElement;\n }\n\n remove(element: T): boolean {\n return this._map.delete(element) !== undefined;\n }\n\n contains(element: T): boolean {\n return this._map.has(element);\n }\n\n // ========================================================================\n // Bulk operations\n // ========================================================================\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n if (this.add(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n removeAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n if (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = this.setOf(other);\n const toRemove: T[] = [];\n\n for (const element of this) {\n if (!toRetain.contains(element)) {\n toRemove.push(element);\n }\n }\n\n let modified = false;\n for (const element of toRemove) {\n this.remove(element);\n modified = true;\n }\n\n return modified;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n clear(): void {\n this._map.clear();\n }\n\n // ========================================================================\n // Set operations (mathematical)\n // ========================================================================\n\n /**\n * This method gives a new set that is the union of this set and the other set.\n * The new set contains all elements from both sets.\n */\n union(other: Iterable<T>): HashSet<T> {\n const result = this.clone();\n result.addAll(other);\n return result;\n }\n\n /**\n * This method gives a new set that is the intersection of this set and the other set.\n * The new set contains only elements present in both sets.\n */\n intersection(other: Iterable<T>): HashSet<T> {\n // The loop reads `other` one time, so a generator gives all of its elements\n const others = this.setOf(other);\n const result = this.empty();\n for (const element of this) {\n if (others.contains(element)) {\n result.add(element);\n }\n }\n return result;\n }\n\n /**\n * This method gives a new set that is the difference of this set and the other set.\n * The new set contains elements in this set but not in the other set.\n */\n difference(other: Iterable<T>): HashSet<T> {\n const result = this.clone();\n result.removeAll(other);\n return result;\n }\n\n /**\n * This method gives a new set that is the symmetric difference of this set and the other set.\n * The new set contains elements in either set but not in both.\n */\n symmetricDifference(other: Iterable<T>): HashSet<T> {\n // The union and the intersection each read `other`, so read it one time first\n const others = this.setOf(other);\n const result = this.union(others);\n const inter = this.intersection(others);\n result.removeAll(inter);\n return result;\n }\n\n /**\n * This method gives true if this set is a subset of the other set.\n * All elements in this set are also in the other set.\n */\n isSubsetOf(other: Iterable<T>): boolean {\n const otherSet = this.setOf(other);\n\n for (const element of this) {\n if (!otherSet.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * This method gives true if this set is a superset of the other set.\n * All elements in the other set are also in this set.\n */\n isSupersetOf(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * This method gives true if this set and the other set have no elements in common.\n */\n isDisjointFrom(other: Iterable<T>): boolean {\n for (const element of other) {\n if (this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n *[Symbol.iterator](): Iterator<T> {\n for (const entry of this._map) {\n yield entry.key;\n }\n }\n\n forEach(action: (element: T, index: number) => void): void {\n let index = 0;\n for (const element of this) {\n action(element, index++);\n }\n }\n\n toArray(): T[] {\n return Array.from(this);\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n /**\n * This method makes a shallow copy of this set.\n */\n clone(): HashSet<T> {\n return this.setOf(this);\n }\n\n /**\n * This method makes an empty set with the equality and the hash function of this set.\n * Before, the inner sets kept only the equality, so they did not find an element with a custom hash.\n */\n private empty(): HashSet<T> {\n return new HashSet<T>({ eq: this._eq, hash: this._hash });\n }\n\n /** This method makes a set of the elements, with the equality and the hash function of this set. */\n private setOf(elements: Iterable<T>): HashSet<T> {\n const set = this.empty();\n set.addAll(elements);\n return set;\n }\n\n /**\n * This method gives statistics about the underlying hash table.\n */\n getStats(): ReturnType<HashMap<T, symbol>[\"getStats\"]> {\n return this._map.getStats();\n }\n\n /**\n * This method gives a string representation for debugging.\n */\n toString(): string {\n return `HashSet{${this.toArray().join(\", \")}}`;\n }\n}\n\n/**\n * Factory function to make a HashSet.\n *\n * @example\n * const set = hashSet<number>()\n * const setFromArray = hashSet([1, 2, 3, 2, 1]) // {1, 2, 3}\n * const setWithOptions = hashSet<string>({ initialCapacity: 32 })\n */\nexport function hashSet<T>(\n optionsOrElements?: HashSetOptions<T> | Iterable<T>\n): HashSet<T> {\n // Check if it's an iterable (not options)\n if (optionsOrElements && Symbol.iterator in optionsOrElements) {\n const set = new HashSet<T>();\n set.addAll(optionsOrElements as Iterable<T>);\n return set;\n }\n\n return new HashSet<T>(optionsOrElements as HashSetOptions<T>);\n}\n","/**\n * PriorityQueue implementation - A binary heap-based priority queue.\n *\n * Elements are ordered according to their natural ordering (through a comparator).\n * The head of the queue is the least element according to the comparator.\n * This module gives O(log n) enqueue and O(log n) dequeue operations.\n * Mirrors java.util.PriorityQueue.\n *\n * @example\n * const pq = priorityQueue<number>((a, b) => a - b) // Min heap\n * pq.offer(5)\n * pq.offer(2)\n * pq.offer(8)\n * pq.poll() // 2 (smallest element)\n */\n\nimport type { PriorityQueue as IPriorityQueue } from \"../interfaces/queue.js\";\nimport type { Eq, Compare } from \"../core/traits.js\";\nimport { defaultEq, defaultCompare } from \"../utils/defaults.js\";\n\n/**\n * Options for making a PriorityQueue.\n */\nexport interface PriorityQueueOptions<T> {\n /**\n * Initial capacity of the heap.\n * @default 11\n */\n initialCapacity?: number;\n\n /**\n * Comparator for ordering elements.\n * Lower values have higher priority (min heap).\n * @default defaultCompare\n */\n compare?: Compare<T>;\n\n /**\n * Equality function for elements.\n * @default defaultEq\n */\n eq?: Eq<T>;\n}\n\n/**\n * PriorityQueue<T> - Binary heap implementation of priority queue.\n *\n * Elements are always retrieved in priority order (according to comparator).\n * Not a FIFO queue - order depends on priority, not insertion order.\n *\n * The heap is a min heap by default (smallest element has highest priority).\n * For max heap, use reversed comparator: (a, b) => compare(b, a)\n *\n * Not thread-safe. Use synchronized() behavior for concurrent access.\n */\nexport class PriorityQueue<T> implements IPriorityQueue<T> {\n private _heap: T[];\n private readonly _compare: Compare<T>;\n private readonly _eq: Eq<T>;\n\n constructor(options: PriorityQueueOptions<T> = {}) {\n const {\n compare = defaultCompare,\n eq = defaultEq,\n } = options;\n\n // The heap starts empty: a JavaScript array grows by itself, so initialCapacity is only a\n // hint. (Before, `new Array(initialCapacity)` made 11 holes: an empty queue had size 11,\n // and the heap compared holes. BUGS-2026-07 C9.)\n this._heap = [];\n this._compare = compare;\n this._eq = eq;\n }\n\n // ========================================================================\n // Size\n // ========================================================================\n\n get size(): number {\n return this._heap.length;\n }\n\n get isEmpty(): boolean {\n return this._heap.length === 0;\n }\n\n get eq(): Eq<T> {\n return this._eq;\n }\n\n get compare(): Compare<T> {\n return this._compare;\n }\n\n get comparator(): Compare<T> {\n return this._compare;\n }\n\n // ========================================================================\n // Priority queue operations\n // ========================================================================\n\n offer(element: T): boolean {\n this._heap.push(element);\n this.bubbleUp(this._heap.length - 1);\n return true;\n }\n\n poll(): T {\n if (this.isEmpty) {\n throw new Error(\"Priority queue is empty\");\n }\n return this.pollOrUndefined()!;\n }\n\n pollOrUndefined(): T | undefined {\n if (this.isEmpty) {\n return undefined;\n }\n\n const result = this._heap[0];\n\n if (this._heap.length === 1) {\n this._heap.pop();\n } else {\n this._heap[0] = this._heap.pop()!;\n this.bubbleDown(0);\n }\n\n return result;\n }\n\n peek(): T {\n if (this.isEmpty) {\n throw new Error(\"Priority queue is empty\");\n }\n return this._heap[0]!;\n }\n\n peekOrUndefined(): T | undefined {\n return this.isEmpty ? undefined : this._heap[0];\n }\n\n // ========================================================================\n // Queue interface compatibility\n // ========================================================================\n\n enqueue(element: T): boolean {\n return this.offer(element);\n }\n\n dequeue(): T {\n return this.poll();\n }\n\n // ========================================================================\n // Collection operations\n // ========================================================================\n\n add(element: T): boolean {\n return this.offer(element);\n }\n\n addAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n this.offer(element);\n modified = true;\n }\n return modified;\n }\n\n contains(element: T): boolean {\n for (const item of this._heap) {\n if (this._eq(item, element)) {\n return true;\n }\n }\n return false;\n }\n\n containsAll(other: Iterable<T>): boolean {\n for (const element of other) {\n if (!this.contains(element)) {\n return false;\n }\n }\n return true;\n }\n\n remove(element: T): boolean {\n const index = this._heap.findIndex((item) => this._eq(item, element));\n if (index === -1) {\n return false;\n }\n\n if (index === this._heap.length - 1) {\n this._heap.pop();\n } else {\n this._heap[index] = this._heap.pop()!;\n this.bubbleDown(index);\n this.bubbleUp(index);\n }\n\n return true;\n }\n\n removeAll(other: Iterable<T>): boolean {\n let modified = false;\n for (const element of other) {\n while (this.remove(element)) {\n modified = true;\n }\n }\n return modified;\n }\n\n retainAll(other: Iterable<T>): boolean {\n const toRetain = new Set(other);\n const newHeap: T[] = [];\n\n for (const element of this._heap) {\n let shouldRetain = false;\n for (const retainElement of toRetain) {\n if (this._eq(element, retainElement)) {\n shouldRetain = true;\n break;\n }\n }\n if (shouldRetain) {\n newHeap.push(element);\n }\n }\n\n const modified = newHeap.length !== this._heap.length;\n this._heap = newHeap;\n this.heapify();\n\n return modified;\n }\n\n clear(): void {\n this._heap = [];\n }\n\n // ========================================================================\n // Iteration\n // ========================================================================\n\n /**\n * Iterator gives elements in arbitrary order (not priority order).\n * To get elements in priority order, repeatedly call poll().\n */\n *[Symbol.iterator](): Iterator<T> {\n yield* this._heap;\n }\n\n forEach(action: (element: T, index: number) => void): void {\n this._heap.forEach((element, index) => action(element, index));\n }\n\n /**\n * This method gives elements in arbitrary heap order (not sorted).\n */\n toArray(): T[] {\n return this._heap.slice();\n }\n\n /**\n * This method gives elements in priority order (sorted).\n * This is a destructive operation that drains the queue.\n */\n toSortedArray(): T[] {\n const result: T[] = [];\n const clone = this.clone();\n\n while (!clone.isEmpty) {\n result.push(clone.poll());\n }\n\n return result;\n }\n\n // ========================================================================\n // Heap operations\n // ========================================================================\n\n /**\n * This method bubbles an element up the heap to maintain heap property.\n */\n private bubbleUp(index: number): void {\n const element = this._heap[index]!;\n\n while (index > 0) {\n const parentIndex = Math.floor((index - 1) / 2);\n const parent = this._heap[parentIndex]!;\n\n if (this._compare(element, parent) >= 0) {\n break;\n }\n\n this._heap[index] = parent;\n index = parentIndex;\n }\n\n this._heap[index] = element;\n }\n\n /**\n * This method bubbles an element down the heap to maintain heap property.\n *\n * The element moves down through a hole: a smaller child moves up into the hole, and the\n * element goes into the last hole. The children are compared with the element.\n * Before, they were compared with `_heap[index]`. After the first step, that value is a copy of\n * the child that moved up. Thus a poll could leave a larger element above a smaller one.\n */\n private bubbleDown(index: number): void {\n const length = this._heap.length;\n const element = this._heap[index]!;\n\n while (true) {\n const leftChildIndex = 2 * index + 1;\n const rightChildIndex = 2 * index + 2;\n if (leftChildIndex >= length) {\n break;\n }\n\n let childIndex = leftChildIndex;\n if (\n rightChildIndex < length &&\n this._compare(this._heap[rightChildIndex]!, this._heap[leftChildIndex]!) < 0\n ) {\n childIndex = rightChildIndex;\n }\n\n if (this._compare(this._heap[childIndex]!, element) >= 0) {\n break;\n }\n\n this._heap[index] = this._heap[childIndex]!;\n index = childIndex;\n }\n\n this._heap[index] = element;\n }\n\n /**\n * This method rebuilds the heap from an arbitrary array.\n * This method uses Floyd's algorithm (O(n) time).\n */\n private heapify(): void {\n // Start from last non-leaf node and bubble down\n for (let i = Math.floor(this._heap.length / 2) - 1; i >= 0; i--) {\n this.bubbleDown(i);\n }\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n /**\n * This method makes a shallow copy of this priority queue.\n */\n clone(): PriorityQueue<T> {\n const clone = new PriorityQueue<T>({\n compare: this._compare,\n eq: this._eq,\n });\n clone._heap = this._heap.slice();\n return clone;\n }\n\n /**\n * This method validates the heap property (for debugging).\n * This method gives true if the heap is valid.\n */\n validate(): boolean {\n for (let i = 0; i < this._heap.length; i++) {\n const leftChildIndex = 2 * i + 1;\n const rightChildIndex = 2 * i + 2;\n\n if (\n leftChildIndex < this._heap.length &&\n this._compare(this._heap[i]!, this._heap[leftChildIndex]!) > 0\n ) {\n return false;\n }\n\n if (\n rightChildIndex < this._heap.length &&\n this._compare(this._heap[i]!, this._heap[rightChildIndex]!) > 0\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * This method gives a string representation for debugging.\n */\n toString(): string {\n return `PriorityQueue[${this._heap.join(\", \")}]`;\n }\n}\n\n/**\n * Factory function to make a PriorityQueue.\n *\n * @example\n * // Min heap (default)\n * const minHeap = priorityQueue<number>()\n *\n * // Max heap\n * const maxHeap = priorityQueue<number>((a, b) => b - a)\n *\n * // From array\n * const pq = priorityQueue([5, 2, 8, 1, 9])\n *\n * // With custom comparator\n * const pq = priorityQueue<Task>((a, b) => a.priority - b.priority)\n */\nexport function priorityQueue<T>(\n optionsOrElementsOrComparator?:\n | PriorityQueueOptions<T>\n | Iterable<T>\n | Compare<T>\n): PriorityQueue<T> {\n // If it's a function, treat it as a comparator\n if (typeof optionsOrElementsOrComparator === \"function\") {\n return new PriorityQueue<T>({\n compare: optionsOrElementsOrComparator as Compare<T>,\n });\n }\n\n // Check if it's an iterable (not options)\n if (optionsOrElementsOrComparator && Symbol.iterator in optionsOrElementsOrComparator) {\n const pq = new PriorityQueue<T>();\n pq.addAll(optionsOrElementsOrComparator as Iterable<T>);\n return pq;\n }\n\n return new PriorityQueue<T>(\n optionsOrElementsOrComparator as PriorityQueueOptions<T>\n );\n}\n","/**\n * SummaryTree: the class form of the summary tree, a persistent sequence of leaves with a summary of each part.\n *\n * The class wraps the plain functions of the entry `@mark1russell7/collections/summary-tree`. Its `record` is the\n * plain record that those functions take. A bundle that uses the class keeps each of its methods, so a program that\n * calls only a few operations imports the functions instead.\n *\n * @example\n * // The number of leaves and the total length of the strings\n * const spec = {\n * monoid: { empty: { count: 0, length: 0 }, combine: (a, b) => ({ count: a.count + b.count, length: a.length + b.length }) },\n * measure: (leaf: string) => ({ count: 1, length: leaf.length }),\n * };\n * const tree = summaryTree(spec, [\"ab\", \"cde\", \"f\"]);\n * tree.summary; // { count: 3, length: 6 }\n * const [left, right] = tree.split((prefix) => prefix.length > 2); // left: [\"ab\"], right: [\"cde\", \"f\"]\n */\n\nimport * as Tree from \"../summary-tree/functions.js\";\nimport type { SummaryLocation, SummaryNode, SummarySearch, SummarySpec, SummaryTreeRecord } from \"../summary-tree/functions.js\";\n\nexport type { SummaryLocation, SummaryMonoid, SummaryNode, SummarySearch, SummarySpec, SummaryTreeRecord } from \"../summary-tree/functions.js\";\n\n/**\n * A persistent sequence of leaves with a summary of each part. Make one with `summaryTree`. Each method that changes\n * the sequence gives a new tree.\n */\nexport class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {\n /** The plain record of the tree: its spec and its root. The functions of the entry `./summary-tree` take it. */\n readonly record: SummaryTreeRecord<Leaf, Summary>;\n\n private constructor(record: SummaryTreeRecord<Leaf, Summary>) {\n this.record = record;\n }\n\n /** This function makes a tree of a spec from leaves, as `summaryTree` does. */\n static of<Leaf, Summary>(spec: SummarySpec<Leaf, Summary>, leaves: Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {\n return new SummaryTree(Tree.of(spec, leaves));\n }\n\n /** This function wraps a plain record of the entry `./summary-tree` in a tree. It does not copy the nodes. */\n static fromRecord<Leaf, Summary>(record: SummaryTreeRecord<Leaf, Summary>): SummaryTree<Leaf, Summary> {\n return new SummaryTree(record);\n }\n\n private wrap(record: SummaryTreeRecord<Leaf, Summary>): SummaryTree<Leaf, Summary> {\n return record === this.record ? this : new SummaryTree(record);\n }\n\n /** The spec of the tree: its monoid and its measure. */\n get spec(): SummarySpec<Leaf, Summary> {\n return this.record.spec;\n }\n\n /** The number of leaves. */\n get size(): number {\n return Tree.size(this.record);\n }\n\n get isEmpty(): boolean {\n return Tree.isEmpty(this.record);\n }\n\n /** The summary of all the leaves, in their order. An empty tree has the summary `monoid.empty`. */\n get summary(): Summary {\n return Tree.summary(this.record);\n }\n\n /** The height of the tree: 0 for an empty tree. The height is at most 1.45 log2(size + 2). */\n get height(): number {\n return Tree.height(this.record);\n }\n\n /**\n * This function gives the leaf at an index, or `undefined` when the index is not in the tree. A negative index counts\n * from the end, as `Array.prototype.at` does.\n */\n at(index: number): Leaf | undefined {\n return Tree.at(this.record, index);\n }\n\n /** This function gives the summary of the leaves from `start` to `end`, with `end` not included. */\n summaryOf(start = 0, end: number = this.size): Summary {\n return Tree.summaryOf(this.record, start, end);\n }\n\n /** This function gives the tree of the leaves of this tree, then the leaves of `other`. The two trees must have the same spec. */\n concat(other: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.concat(this.record, recordOf(other)));\n }\n\n /** This function splits the tree into its first `index` leaves and the other leaves. */\n splitAt(index: number): [SummaryTree<Leaf, Summary>, SummaryTree<Leaf, Summary>] {\n const [left, right] = Tree.splitAt(this.record, index);\n return [this.wrap(left), this.wrap(right)];\n }\n\n /**\n * This function splits the tree before the first leaf whose prefix summary satisfies the predicate. The prefix of a\n * leaf includes the leaf. The predicate must be monotone: after it is true for a prefix, it is true for each longer\n * prefix. When no prefix satisfies it, the right tree is empty.\n */\n split(predicate: (prefix: Summary) => boolean): [SummaryTree<Leaf, Summary>, SummaryTree<Leaf, Summary>] {\n const [left, right] = Tree.split(this.record, predicate);\n return [this.wrap(left), this.wrap(right)];\n }\n\n /**\n * This function finds the first leaf whose prefix summary satisfies a monotone predicate, as `split` does. It changes\n * nothing. It gives `undefined` when no prefix satisfies the predicate.\n */\n search(predicate: (prefix: Summary) => boolean): SummarySearch<Leaf, Summary> | undefined {\n return Tree.search(this.record, predicate);\n }\n\n /**\n * This function finds the leaf that holds a position of an additive key, and it calls no `combine`. The key must be\n * additive and not negative: `key(combine(a, b))` is `key(a) + key(b)`. The function descends by the key of each left\n * subtree and of each leaf, and subtracts it from the target. It gives the first leaf whose prefix key is more than\n * the target, or `undefined` when the target is not in `[0, key(summary))`.\n *\n * @example\n * // The leaf and the offset in it of the code unit at position 1000 of a rope\n * const at = rope.locate((s) => s.length, 1000);\n */\n locate(key: (summary: Summary) => number, target: number): SummaryLocation<Leaf> | undefined {\n return Tree.locate(this.record, key, target);\n }\n\n /** This function gives the tree of the leaves from `start` to `end`, with `end` not included. A negative index counts from the end. */\n slice(start = 0, end: number = this.size): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.slice(this.record, start, end));\n }\n\n /**\n * This function removes `deleteCount` leaves at `start` and puts the leaves of `inserted` there, as\n * `Array.prototype.splice` does. It gives the new tree, not the removed leaves.\n */\n splice(start: number, deleteCount: number = this.size, inserted: SummaryTree<Leaf, Summary> | Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.splice(this.record, start, deleteCount, recordOf(inserted)));\n }\n\n /** This function puts the leaves of `inserted` before the leaf at `index`. */\n insert(index: number, inserted: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.insert(this.record, index, recordOf(inserted)));\n }\n\n /** This function removes the leaves from `start` to `end`, with `end` not included. */\n remove(start: number, end: number = this.size): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.remove(this.record, start, end));\n }\n\n /**\n * This function replaces the leaf at an index. A negative index counts from the end, as `Array.prototype.with` does.\n * An index that is not in the tree changes nothing. It copies only the path to the leaf, and it does not call\n * `spec.merge`.\n */\n set(index: number, leaf: Leaf): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.set(this.record, index, leaf));\n }\n\n /** This function adds leaves after the last leaf. */\n append(...leaves: Leaf[]): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.append(this.record, ...leaves));\n }\n\n /** This function adds leaves before the first leaf. */\n prepend(...leaves: Leaf[]): SummaryTree<Leaf, Summary> {\n return this.wrap(Tree.prepend(this.record, ...leaves));\n }\n\n /** This function gives the leaves in their order. */\n [Symbol.iterator](): Iterator<Leaf> {\n return Tree.leaves(this.record);\n }\n\n /** This function gives the leaves in an array. */\n toArray(): Leaf[] {\n return Tree.toArray(this.record);\n }\n}\n\n/** This function gives the record of a tree, or the leaves when they are not a tree. */\nfunction recordOf<Leaf, Summary>(leaves: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTreeRecord<Leaf, Summary> | Iterable<Leaf> {\n return leaves instanceof SummaryTree ? leaves.record : leaves;\n}\n\n/**\n * This function makes a persistent tree of leaves with a summary of each part. Use the same `spec` object for each\n * tree that `concat` or `splice` joins.\n */\nexport function summaryTree<Leaf, Summary>(spec: SummarySpec<Leaf, Summary>, leaves: Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {\n return SummaryTree.of(spec, leaves);\n}\n\n/**\n * @internal This function examines the invariants of a tree: the AVL balance, the heights, the sizes and the\n * summaries. It gives a list of the faults, empty when there is no fault. The tests use it.\n */\nexport function summaryTreeFaults<Leaf, Summary>(\n tree: SummaryTree<Leaf, Summary> | SummaryTreeRecord<Leaf, Summary>,\n equal: (a: Summary, b: Summary) => boolean,\n): string[] {\n const { spec, root } = tree instanceof SummaryTree ? tree.record : tree;\n const { combine, empty } = spec.monoid;\n const heightOf = (n: SummaryNode<Leaf, Summary> | null): number => (n === null ? 0 : n.height);\n const sizeOf = (n: SummaryNode<Leaf, Summary> | null): number => (n === null ? 0 : n.size);\n const summaryOf = (n: SummaryNode<Leaf, Summary> | null): Summary => (n === null ? empty : n.summary);\n const faults: string[] = [];\n const visit = (node: SummaryNode<Leaf, Summary> | null, path: string): void => {\n if (node === null) return;\n visit(node.left, `${path}L`);\n visit(node.right, `${path}R`);\n const hl = heightOf(node.left);\n const hr = heightOf(node.right);\n if (Math.abs(hl - hr) > 1) faults.push(`${path}: balance ${hl - hr}`);\n if (node.height !== 1 + Math.max(hl, hr)) faults.push(`${path}: height ${node.height}`);\n if (node.size !== sizeOf(node.left) + 1 + sizeOf(node.right)) faults.push(`${path}: size ${node.size}`);\n const inner = combine(summaryOf(node.left), spec.measure(node.leaf));\n if (!equal(node.inner, inner)) faults.push(`${path}: inner`);\n if (!equal(node.summary, combine(inner, summaryOf(node.right)))) faults.push(`${path}: summary`);\n };\n visit(root, \"^\");\n return faults;\n}\n","/**\n * The check of a capacity, for each layer and class that has a maximum size.\n */\n\n/**\n * This function gives the capacity when it is a positive whole number. Otherwise it throws a\n * `RangeError`. A capacity of `NaN` makes a comparison `size >= capacity` always false, so a\n * structure with that capacity grows without a limit. A capacity of 0 or less, or a fraction,\n * has no clear meaning.\n *\n * @param capacity - The capacity to check.\n * @param owner - The name of the layer or class, for the message of the error.\n * @returns The same capacity.\n * @throws RangeError when the capacity is not a positive whole number.\n */\nexport function checkCapacity(capacity: number, owner: string): number {\n if (!Number.isSafeInteger(capacity) || capacity < 1) {\n throw new RangeError(`${owner}: the capacity must be a positive whole number, not ${String(capacity)}`);\n }\n return capacity;\n}\n","/**\n * Bounded behavior: this module enforces capacity limits on collections.\n *\n * This module wraps collections to prevent them from exceeding a maximum size.\n * This module gives various overflow policies to handle full collections.\n *\n * @example\n * const list = compose(\n * boundedList<number>({ capacity: 100, policy: 'drop-oldest' })\n * )(arrayList<number>())\n *\n * // Add 101 elements - first element will be dropped\n * for (let i = 0; i < 101; i++) {\n * list.add(i)\n * }\n */\n\nimport { checkCapacity } from \"../core/capacity.js\";\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue, Deque } from \"../interfaces/queue.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { removals, removalSource, type ElementRemoval, type MapRemoval } from \"../core/removals.js\";\nimport type { Collection } from \"../interfaces/collection.js\";\nimport type {\n OverflowPolicy,\n OverflowHandler,\n OverflowContext,\n} from \"../core/policies.js\";\n\n/**\n * Options for bounded behavior.\n */\nexport interface BoundedOptions<T> {\n /**\n * Maximum number of elements the collection can hold.\n */\n capacity: number;\n\n /**\n * Policy for handling overflow when collection is full.\n * @default 'throw'\n */\n policy?: OverflowPolicy;\n\n /**\n * Optional callback invoked when overflow occurs.\n * The behavior calls this function before it applies the policy.\n */\n onOverflow?: OverflowHandler<T>;\n}\n\n/**\n * Marker interface for bounded collections.\n */\nexport interface BoundedCollection {\n readonly capacity: number;\n readonly isFull: boolean;\n readonly remainingCapacity: number;\n}\n\n/**\n * This function makes a bounded List middleware.\n *\n * Intercepts add operations to enforce capacity limits.\n * This function supports multiple overflow policies.\n */\nexport function boundedList<T>(\n options: BoundedOptions<T>\n): Middleware<List<T>, List<T> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedList\");\n\n return (next: List<T>): List<T> & BoundedCollection => {\n const source = removalSource<ElementRemoval<T>>(next);\n // An unshift puts the element at the front, so drop-oldest drops the last element for it\n const handleOverflow = (element: T, dropFrom: \"first\" | \"last\" = \"first\"): void => {\n // Call overflow handler if provided\n if (onOverflow) {\n const context: OverflowContext<T> = {\n newElement: element,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n };\n onOverflow(context);\n }\n\n // Apply policy\n switch (policy) {\n case \"throw\":\n throw new Error(`List is full (capacity: ${capacity})`);\n\n case \"drop-oldest\":\n // Remove one element: the first, or the last for an unshift\n if (!next.isEmpty) {\n const value = dropFrom === \"last\" ? next.pop() : next.shift();\n source.emit({ value, end: dropFrom, reason: \"drop\" });\n }\n break;\n\n case \"drop-newest\":\n // Don't add the new element (do nothing)\n return;\n\n case \"reject\":\n // Silently reject (return false for add operations)\n return;\n\n case \"grow\":\n // Allow growth (do nothing, element will be added)\n return;\n\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n // After drop-oldest removed the first element, an index of the caller is one place lower\n const shifted = (index: number): number => (policy === \"drop-oldest\" ? Math.max(0, index - 1) : index);\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n // Capacity property\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") {\n return capacity;\n }\n\n // isFull property\n if (prop === \"isFull\") {\n return target.size >= capacity;\n }\n\n // remainingCapacity property\n if (prop === \"remainingCapacity\") {\n return Math.max(0, capacity - target.size);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n // Intercept methods that add elements\n if (typeof value === \"function\") {\n switch (prop) {\n case \"add\":\n return function (element: T): boolean {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return false;\n }\n }\n return (value as Function).call(target, element);\n };\n\n case \"push\":\n return function (element: T): void {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return;\n }\n }\n (value as Function).call(target, element);\n };\n\n case \"unshift\":\n return function (element: T): void {\n if (target.size >= capacity && policy !== \"grow\") {\n // One element goes: the last one (before, the first and the last went: audit pass 2)\n handleOverflow(element, \"last\");\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return;\n }\n }\n (value as Function).call(target, element);\n };\n\n case \"insert\":\n return function (index: number, element: T): void {\n let at = index;\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return;\n }\n at = shifted(at);\n }\n (value as Function).call(target, at, element);\n };\n\n case \"addAll\":\n case \"insertAll\":\n return function (...args: any[]): boolean {\n const elements = args[args.length - 1] as Iterable<T>;\n const elementsArray = Array.from(elements);\n\n // Check if adding all elements would exceed capacity\n if (target.size + elementsArray.length > capacity && policy !== \"grow\") {\n // Add elements one by one with overflow handling. An insert keeps the order of\n // the elements, at an index that follows each drop.\n let added = false;\n let at = args[0] as number;\n for (const element of elementsArray) {\n if (target.size >= capacity) {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n break;\n }\n at = shifted(at);\n }\n if (prop === \"addAll\") {\n target.add(element);\n } else {\n target.insert(at, element);\n at++;\n }\n added = true;\n }\n return added;\n }\n\n return (value as Function).apply(target, args);\n };\n }\n }\n\n return value;\n },\n }) as List<T> & BoundedCollection;\n };\n}\n\n/**\n * This function adds each element with `add`, one after the other, until `add` refuses one.\n * It gives true when one element goes in. A throw of `add` stops it, and the earlier elements stay.\n */\nfunction addEach<T>(elements: Iterable<T>, add: (element: T) => boolean): boolean {\n let added = false;\n for (const element of Array.from(elements)) {\n if (!add(element)) break;\n added = true;\n }\n return added;\n}\n\n/**\n * This function makes a bounded Queue middleware.\n */\nexport function boundedQueue<T>(\n options: BoundedOptions<T>\n): Middleware<Queue<T>, Queue<T> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedQueue\");\n\n return (next: Queue<T>): Queue<T> & BoundedCollection => {\n const source = removalSource<ElementRemoval<T>>(next);\n const handleOverflow = (element: T): void => {\n if (onOverflow) {\n const context: OverflowContext<T> = {\n newElement: element,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n };\n onOverflow(context);\n }\n\n switch (policy) {\n case \"throw\":\n throw new Error(`Queue is full (capacity: ${capacity})`);\n case \"drop-oldest\":\n if (!next.isEmpty) {\n source.emit({ value: next.poll() as T, end: \"first\", reason: \"drop\" });\n }\n break;\n case \"drop-newest\":\n case \"reject\":\n return;\n case \"grow\":\n return;\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") return capacity;\n if (prop === \"isFull\") return target.size >= capacity;\n if (prop === \"remainingCapacity\") return Math.max(0, capacity - target.size);\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"offer\":\n case \"enqueue\":\n case \"add\":\n return function (element: T): boolean {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return false;\n }\n }\n return (value as Function).call(target, element);\n };\n\n // The base addAll goes past the bound, so each element goes through add of this proxy (C10)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => (receiver as Queue<T>).add(element));\n };\n }\n }\n\n return value;\n },\n }) as Queue<T> & BoundedCollection;\n };\n}\n\n/**\n * This function makes a bounded Deque middleware.\n */\nexport function boundedDeque<T>(\n options: BoundedOptions<T>\n): Middleware<Deque<T>, Deque<T> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedDeque\");\n\n return (next: Deque<T>): Deque<T> & BoundedCollection => {\n const source = removalSource<ElementRemoval<T>>(next);\n // An insert at the front drops the last element, as unshift of boundedList does (C10)\n const handleOverflow = (element: T, dropFrom: \"first\" | \"last\"): void => {\n if (onOverflow) {\n const context: OverflowContext<T> = {\n newElement: element,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n };\n onOverflow(context);\n }\n\n switch (policy) {\n case \"throw\":\n throw new Error(`Deque is full (capacity: ${capacity})`);\n case \"drop-oldest\":\n if (!next.isEmpty) {\n const value = dropFrom === \"last\" ? next.removeLast() : next.removeFirst();\n source.emit({ value, end: dropFrom, reason: \"drop\" });\n }\n break;\n case \"drop-newest\":\n case \"reject\":\n return;\n case \"grow\":\n return;\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") return capacity;\n if (prop === \"isFull\") return target.size >= capacity;\n if (prop === \"remainingCapacity\") return Math.max(0, capacity - target.size);\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"addFirst\":\n case \"addLast\":\n case \"offerFirst\":\n case \"offerLast\":\n case \"push\":\n case \"offer\":\n case \"add\":\n return function (element: T): any {\n if (target.size >= capacity && policy !== \"grow\") {\n handleOverflow(element, prop === \"addFirst\" || prop === \"offerFirst\" ? \"last\" : \"first\");\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return prop.startsWith(\"offer\") || prop === \"add\" ? false : undefined;\n }\n }\n return (value as Function).call(target, element);\n };\n\n // The base addAll goes past the bound, so each element goes through add of this proxy (C10)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => (receiver as Deque<T>).add(element));\n };\n }\n }\n\n return value;\n },\n }) as Deque<T> & BoundedCollection;\n };\n}\n\n/**\n * This function makes a bounded Map middleware.\n */\nexport function boundedMap<K, V>(\n options: Omit<BoundedOptions<V>, \"onOverflow\"> & {\n onOverflow?: (context: Omit<OverflowContext<V>, \"newElement\"> & { key: K; value: V }) => void;\n }\n): Middleware<MapLike<K, V>, MapLike<K, V> & BoundedCollection> {\n const { policy = \"throw\", onOverflow } = options;\n const capacity = checkCapacity(options.capacity, \"boundedMap\");\n\n return (next: MapLike<K, V>): MapLike<K, V> & BoundedCollection => {\n let insertionOrder: K[] = []; // Track insertion order for drop-oldest\n // A removal below (for example an eviction of lruMap) takes its key out of the order\n const source = removalSource<MapRemoval<K, V>>(next, ({ key }) => {\n insertionOrder = insertionOrder.filter((k) => !next.keyEq(k, key));\n });\n\n const handleOverflow = (key: K, value: V): void => {\n if (onOverflow) {\n onOverflow({\n key,\n value,\n currentSize: next.size,\n capacity,\n timestamp: Date.now(),\n });\n }\n\n switch (policy) {\n case \"throw\":\n throw new Error(`Map is full (capacity: ${capacity})`);\n case \"drop-oldest\":\n // Remove oldest key\n // The removal channel below keeps the order exact. A layer below with no channel can remove a key\n // without this layer seeing it, so a drop skips each key that is gone.\n while (insertionOrder.length > 0) {\n const oldestKey = insertionOrder.shift()!;\n if (!next.has(oldestKey)) continue;\n const value = next.get(oldestKey);\n next.delete(oldestKey);\n source.emit({ key: oldestKey, value, reason: \"drop\" });\n break;\n }\n break;\n case \"drop-newest\":\n case \"reject\":\n return;\n case \"grow\":\n return;\n case \"block\":\n throw new Error(\"Block policy not supported for sync collections\");\n default:\n throw new Error(`Unknown overflow policy: ${policy}`);\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) return source.channel;\n if (prop === \"capacity\") return capacity;\n if (prop === \"isFull\") return target.size >= capacity;\n if (prop === \"remainingCapacity\") return Math.max(0, capacity - target.size);\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"set\":\n return function (key: K, val: V): V | undefined {\n const hadKey = target.has(key);\n\n if (!hadKey && target.size >= capacity && policy !== \"grow\") {\n handleOverflow(key, val);\n if (policy === \"reject\" || policy === \"drop-newest\") {\n return undefined;\n }\n }\n\n const result = (value as Function).call(target, key, val);\n\n // Track insertion order\n if (!hadKey) {\n insertionOrder.push(key);\n }\n\n return result;\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n const result = (value as Function).call(target, key);\n // Remove from insertion order tracking\n insertionOrder = insertionOrder.filter((k) => !target.keyEq(k, key));\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n insertionOrder = [];\n };\n }\n }\n\n return value;\n },\n }) as MapLike<K, V> & BoundedCollection;\n };\n}\n\n/**\n * Generic bounded collection middleware.\n * Works with any collection type.\n */\nexport function bounded<C extends Collection<any>>(\n options: BoundedOptions<any>\n): Middleware<C, C & BoundedCollection> {\n return boundedList(options) as any;\n}\n","/**\n * Readonly behavior: this module makes immutable views of collections.\n *\n * This module wraps collections to prevent modifications by throwing errors\n * on any mutation try. Mirrors Java's Collections.unmodifiable*() methods.\n *\n * @example\n * const list = compose(\n * readonlyList()\n * )(arrayList([1, 2, 3]))\n *\n * list.get(0) // OK: 1\n * list.add(4) // Error: Cannot modify readonly list\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { ReadonlyList } from \"../interfaces/list.js\";\nimport type { ReadonlyQueue } from \"../interfaces/queue.js\";\nimport type { ReadonlyMapLike } from \"../interfaces/map.js\";\nimport type { ReadonlyCollection } from \"../interfaces/collection.js\";\n\n/**\n * Options for readonly behavior.\n */\nexport interface ReadonlyOptions {\n /**\n * Custom error message to throw on mutation tries.\n * @default 'Cannot modify readonly collection'\n */\n errorMessage?: string;\n}\n\n/**\n * This set holds the names of the methods that mutate collections.\n */\nconst MUTATING_METHODS = new Set([\n // Collection mutations\n \"add\",\n \"addAll\",\n \"remove\",\n \"removeAll\",\n \"retainAll\",\n \"clear\",\n\n // List mutations\n \"set\",\n \"insert\",\n \"insertAll\",\n \"removeAt\",\n \"removeRange\",\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"sort\",\n \"reverse\",\n\n // Queue/Deque mutations\n \"offer\",\n \"offerFirst\",\n \"offerLast\",\n \"poll\",\n \"pollFirst\",\n \"pollLast\",\n \"enqueue\",\n \"dequeue\",\n \"addFirst\",\n \"addLast\",\n \"removeFirst\",\n \"removeLast\",\n\n // Map mutations\n \"set\",\n \"setIfAbsent\",\n \"forcePut\",\n \"pollFirstEntry\",\n \"pollLastEntry\",\n \"delete\",\n \"deleteEntry\",\n \"replace\",\n \"replaceEntry\",\n \"computeIfAbsent\",\n \"computeIfPresent\",\n \"compute\",\n \"merge\",\n \"putAll\",\n\n // Queue changes that give undefined on an empty queue (C27: a readonly view removed an element)\n \"pollOrUndefined\",\n\n // The removal by a test of LRUCache (C31: a readonly view of an LRU cache emptied it)\n \"deleteWhere\",\n\n // The internal changes of the structures of this package. TypeScript marks them private, but a call at run\n // time reaches them. `readonly.test.ts` puts each method of each structure in the reads or in this list.\n \"ensureCapacity\",\n \"trimToSize\",\n \"grow\",\n \"resize\",\n \"removeAtOffset\",\n \"unlinkNode\",\n \"heapify\",\n \"bubbleUp\",\n \"bubbleDown\",\n \"addToEnd\",\n \"moveToEnd\",\n \"removeFromBucket\",\n \"removeFromList\",\n \"deleteNode\",\n \"fixAfterInsertion\",\n \"fixAfterDeletion\",\n \"rotateLeft\",\n \"rotateRight\",\n \"moveToHead\",\n \"removeNode\",\n \"evictLRU\",\n]);\n\n/** Methods that return a view of the collection: the view is readonly too. */\nconst VIEW_METHODS = new Set([\n \"subList\",\n \"subMap\",\n \"subSet\",\n \"headMap\",\n \"tailMap\",\n \"headSet\",\n \"tailSet\",\n \"descendingMap\",\n \"descendingSet\",\n \"inverse\",\n]);\n\n/**\n * This function makes a readonly middleware for any collection type.\n */\nfunction createReadonly<C extends object>(\n errorMessage: string = \"Cannot modify readonly collection\"\n): Middleware<C> {\n return (next: C): C => {\n // The read methods, bound to the collection: one function for each name\n const bound = new Map<PropertyKey, { value: Function; method: Function }>();\n return new Proxy(next, {\n get(target, prop) {\n // A read runs on the collection itself, not on the proxy: a read that changes internal\n // state (a LinkedHashMap with accessOrder moves the entry) does not hit the set trap\n const value = Reflect.get(target, prop, target);\n\n // Block mutating methods\n if (typeof prop === \"string\" && MUTATING_METHODS.has(prop)) {\n if (typeof value === \"function\") {\n return () => {\n throw new Error(errorMessage);\n };\n }\n }\n\n // A view (a sublist, a submap, a head or tail set, a descending map) is readonly too.\n // Before, only subList and subMap were wrapped, and setIfAbsent, pollFirstEntry and\n // pollLastEntry were not blocked (BUGS-2026-07 L14).\n if (typeof value === \"function\" && typeof prop === \"string\" && VIEW_METHODS.has(prop)) {\n return function (this: any, ...args: any[]) {\n const result = value.apply(target, args);\n // Recursively apply readonly to the result\n return createReadonly<typeof result>(errorMessage)(result);\n };\n }\n\n if (typeof value === \"function\") {\n const known = bound.get(prop);\n if (known !== undefined && known.value === value) return known.method;\n const method = (value as Function).bind(target) as Function;\n bound.set(prop, { value, method });\n return method;\n }\n\n return value;\n },\n\n set(_target, _prop, _value, _receiver) {\n // Block property assignments\n throw new Error(errorMessage);\n },\n\n deleteProperty(_target, _prop) {\n // Block property deletions\n throw new Error(errorMessage);\n },\n });\n };\n}\n\n/**\n * This function makes a readonly List middleware.\n *\n * All mutation methods will throw an error.\n * Read operations work normally.\n *\n * @example\n * const readonlyNumbers = compose(\n * readonlyList()\n * )(arrayList([1, 2, 3]))\n */\nexport function readonlyList<T>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyList<T>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly list\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * This function makes a readonly Queue middleware.\n */\nexport function readonlyQueue<T>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyQueue<T>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly queue\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * This function makes a readonly Map middleware.\n */\nexport function readonlyMap<K, V>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyMapLike<K, V>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly map\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * This function makes a readonly Collection middleware.\n *\n * Generic version that works with any collection type.\n */\nexport function readonlyCollection<T>(\n options: ReadonlyOptions = {}\n): Middleware<ReadonlyCollection<T>> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly collection\";\n return createReadonly<any>(errorMessage);\n}\n\n/**\n * Generic readonly middleware.\n * Alias for readonlyCollection.\n */\nexport function readonly<C extends object>(\n options: ReadonlyOptions = {}\n): Middleware<C> {\n const errorMessage = options.errorMessage ?? \"Cannot modify readonly collection\";\n return createReadonly<C>(errorMessage);\n}\n\n/**\n * Alias for Java compatibility: unmodifiableList\n */\nexport const unmodifiableList : typeof readonlyList = readonlyList;\n\n/**\n * Alias for Java compatibility: unmodifiableMap\n */\nexport const unmodifiableMap : typeof readonlyMap = readonlyMap;\n\n/**\n * Alias for Java compatibility: unmodifiableCollection\n */\nexport const unmodifiableCollection : typeof readonlyCollection = readonlyCollection;\n","/**\n * The safe middleware. Each operation that throws on a missing element has a safe form in the property `safe`. The safe\n * form gives an `Optional` or a `Result` of `@mark1russell7/optional`, and does not throw.\n *\n * @example\n * import { isSome } from \"@mark1russell7/optional\";\n *\n * const list = compose(safeList<number>())(arrayList<number>());\n * const value = list.safe.get(10); // an Optional<number>, not an exception\n * if (isSome(value)) console.log(value.value);\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue, Deque } from \"../interfaces/queue.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { none, some, toOptional, tryCatch, type Optional, type Result } from \"@mark1russell7/optional\";\n\n/**\n * Safe operations for List.\n */\nexport interface SafeListOperations<T> {\n /**\n * This method gives the element at an index, as an optional.\n */\n get(index: number): Optional<T>;\n\n /**\n * This method sets the element at an index. It gives a Result with the old value or an error.\n */\n set(index: number, element: T): Result<T, string>;\n\n /**\n * This method removes the element at an index. It gives a Result with the removed value or an error.\n */\n removeAt(index: number): Result<T, string>;\n\n /**\n * This method gives the first element, as an optional.\n */\n first(): Optional<T>;\n\n /**\n * This method gives the last element, as an optional.\n */\n last(): Optional<T>;\n\n /**\n * Pop element, as an optional.\n */\n pop(): Optional<T>;\n\n /**\n * Shift element, as an optional.\n */\n shift(): Optional<T>;\n}\n\n/**\n * Safe operations for Queue.\n */\nexport interface SafeQueueOperations<T> {\n /**\n * This method gives the head element as an optional, and does not remove it.\n */\n peek(): Optional<T>;\n\n /**\n * This method removes the head element and gives it as an optional.\n */\n poll(): Optional<T>;\n\n /**\n * This method dequeues the head element and gives it as an optional.\n */\n dequeue(): Optional<T>;\n}\n\n/**\n * Safe operations for Deque.\n */\nexport interface SafeDequeOperations<T> extends SafeQueueOperations<T> {\n /**\n * This method gives the first element as an optional, and does not remove it.\n */\n peekFirst(): Optional<T>;\n\n /**\n * This method gives the last element as an optional, and does not remove it.\n */\n peekLast(): Optional<T>;\n\n /**\n * This method removes the first element and gives it as an optional.\n */\n pollFirst(): Optional<T>;\n\n /**\n * This method removes the last element and gives it as an optional.\n */\n pollLast(): Optional<T>;\n\n /**\n * This method pops the top element and gives it as an optional.\n */\n pop(): Optional<T>;\n}\n\n/**\n * Safe operations for Map.\n */\nexport interface SafeMapOperations<K, V> {\n /**\n * This method gives the value of a key, as an optional.\n */\n get(key: K): Optional<V>;\n\n /**\n * This method sets the value of a key. It gives a Result with the old value or a success.\n */\n set(key: K, value: V): Result<V | undefined, string>;\n\n /**\n * This method deletes a key. It gives a Result with the deleted value or an error.\n */\n delete(key: K): Result<V | undefined, string>;\n}\n\n/**\n * This function makes a safe List middleware.\n *\n * This function exposes a `safe` property with Optional/Result-based operations.\n */\nexport function safeList<T>(): Middleware<\n List<T>,\n List<T> & { safe: SafeListOperations<T> }\n> {\n return (next: List<T>): List<T> & { safe: SafeListOperations<T> } => {\n const safe: SafeListOperations<T> = {\n get(index: number): Optional<T> {\n return toOptional(tryCatch(() => next.get(index)));\n },\n\n set(index: number, element: T): Result<T, string> {\n return tryCatch(\n () => next.set(index, element),\n (error) => String(error)\n );\n },\n\n removeAt(index: number): Result<T, string> {\n return tryCatch(\n () => next.removeAt(index),\n (error) => String(error)\n );\n },\n\n first(): Optional<T> {\n return next.isEmpty ? none : some(next.first());\n },\n\n last(): Optional<T> {\n return next.isEmpty ? none : some(next.last());\n },\n\n pop(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.pop()));\n },\n\n shift(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.shift()));\n },\n };\n\n // Extend next with safe property\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * This function makes a safe Queue middleware.\n */\nexport function safeQueue<T>(): Middleware<\n Queue<T>,\n Queue<T> & { safe: SafeQueueOperations<T> }\n> {\n return (next: Queue<T>): Queue<T> & { safe: SafeQueueOperations<T> } => {\n const safe: SafeQueueOperations<T> = {\n peek(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.peek()));\n },\n\n poll(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.poll()));\n },\n\n dequeue(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.dequeue()));\n },\n };\n\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * This function makes a safe Deque middleware.\n */\nexport function safeDeque<T>(): Middleware<\n Deque<T>,\n Deque<T> & { safe: SafeDequeOperations<T> }\n> {\n return (next: Deque<T>): Deque<T> & { safe: SafeDequeOperations<T> } => {\n const safe: SafeDequeOperations<T> = {\n peek(): Optional<T> {\n return next.isEmpty ? none : some(next.peekFirst());\n },\n\n poll(): Optional<T> {\n // One poll: before, the test and the result each called pollFirst(), so poll() removed\n // two elements and returned the second (BUGS-2026-07 L12)\n if (next.isEmpty) return none;\n return some(next.pollFirst() as T);\n },\n\n dequeue(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.dequeue()));\n },\n\n peekFirst(): Optional<T> {\n return next.isEmpty ? none : some(next.peekFirst());\n },\n\n peekLast(): Optional<T> {\n return next.isEmpty ? none : some(next.peekLast());\n },\n\n pollFirst(): Optional<T> {\n const result = next.pollFirst();\n return result !== undefined ? some(result) : none;\n },\n\n pollLast(): Optional<T> {\n const result = next.pollLast();\n return result !== undefined ? some(result) : none;\n },\n\n pop(): Optional<T> {\n if (next.isEmpty) return none;\n return toOptional(tryCatch(() => next.pop()));\n },\n };\n\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * This function makes a safe Map middleware.\n */\nexport function safeMap<K, V>(): Middleware<\n MapLike<K, V>,\n MapLike<K, V> & { safe: SafeMapOperations<K, V> }\n> {\n return (\n next: MapLike<K, V>\n ): MapLike<K, V> & { safe: SafeMapOperations<K, V> } => {\n const safe: SafeMapOperations<K, V> = {\n get(key: K): Optional<V> {\n return next.has(key) ? some(next.get(key)) : none;\n },\n\n set(key: K, value: V): Result<V | undefined, string> {\n return tryCatch(\n () => next.set(key, value),\n (error) => String(error)\n );\n },\n\n delete(key: K): Result<V | undefined, string> {\n return tryCatch(\n () => next.delete(key),\n (error) => String(error)\n );\n },\n };\n\n return Object.assign(next, { safe });\n };\n}\n\n/**\n * Generic safe middleware that works with any collection.\n */\nexport function safe<C extends object>(): Middleware<C> {\n // Return as-is for now; specialized versions handle specific types\n return (next: C): C => next;\n}\n","/**\n * Composite map methods built on `has`, `get`, `set` and `delete`.\n *\n * A map behavior (lruMap, ttlMap) intercepts the primitive methods. It gives these\n * implementations for the composite methods, bound to the behavior's own proxy.\n * Thus a call like `setIfAbsent` goes through the behavior's `set` and keeps its rules:\n * capacity and recency for LRU, expiry for TTL. (BUGS-2026-07 L13: the composite methods\n * went straight to the map below, so they bypassed the behavior.)\n *\n * The semantics follow HashMap. One difference: `replaceEntry` and `deleteEntry` compare\n * values with Object.is, not with a map's custom value equality.\n */\n\nimport type { Entry, MapLike } from \"../interfaces/map.js\";\n\ntype AnyFn = (...args: never[]) => unknown;\n\nexport function compositeMapMethod<K, V>(map: MapLike<K, V>, name: PropertyKey): AnyFn | undefined {\n switch (name) {\n case \"setIfAbsent\":\n return ((key: K, value: V): V => {\n if (map.has(key)) return map.get(key);\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"replace\":\n return ((key: K, value: V): V | undefined => (map.has(key) ? map.set(key, value) : undefined)) as AnyFn;\n\n case \"replaceEntry\":\n return ((key: K, oldValue: V, newValue: V): boolean => {\n if (!map.has(key) || !Object.is(map.get(key), oldValue)) return false;\n map.set(key, newValue);\n return true;\n }) as AnyFn;\n\n case \"deleteEntry\":\n return ((key: K, value: V): boolean => {\n if (!map.has(key) || !Object.is(map.get(key), value)) return false;\n map.delete(key);\n return true;\n }) as AnyFn;\n\n case \"computeIfAbsent\":\n return ((key: K, mappingFunction: (key: K) => V): V => {\n if (map.has(key)) return map.get(key);\n const value = mappingFunction(key);\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"computeIfPresent\":\n return ((key: K, remapping: (key: K, value: V) => V | undefined): V | undefined => {\n if (!map.has(key)) return undefined;\n const value = remapping(key, map.get(key));\n if (value === undefined) {\n map.delete(key);\n return undefined;\n }\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"compute\":\n return ((key: K, remapping: (key: K, value: V | undefined) => V | undefined): V | undefined => {\n const present = map.has(key);\n const value = remapping(key, present ? map.get(key) : undefined);\n if (value === undefined) {\n if (present) map.delete(key);\n return undefined;\n }\n map.set(key, value);\n return value;\n }) as AnyFn;\n\n case \"merge\":\n return ((key: K, value: V, remapping: (oldValue: V, newValue: V) => V | undefined): V | undefined => {\n if (!map.has(key)) {\n map.set(key, value);\n return value;\n }\n const merged = remapping(map.get(key), value);\n if (merged === undefined) {\n map.delete(key);\n return undefined;\n }\n map.set(key, merged);\n return merged;\n }) as AnyFn;\n\n case \"putAll\":\n return ((other: Iterable<Entry<K, V>>): void => {\n for (const entry of other) {\n map.set(entry.key, entry.value);\n }\n }) as AnyFn;\n }\n return undefined;\n}\n","/**\n * Evented behavior: this module emits typed events on collection mutations.\n *\n * This module wraps collections to emit events whenever elements are added, removed,\n * or the collection is cleared. This module enables reactive programming patterns.\n *\n * @example\n * const list = compose(\n * eventedList<number>()\n * )(arrayList<number>())\n *\n * list.on('add', ({ value, index }) => {\n * console.log(`Added ${value} at index ${index}`)\n * })\n *\n * list.add(42) // Triggers 'add' event\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue, Deque } from \"../interfaces/queue.js\";\nimport type { Entry, MapLike } from \"../interfaces/map.js\";\nimport type { Collection } from \"../interfaces/collection.js\";\nimport { Emitter, type Unsubscribe } from \"../core/events.js\";\nimport { removalsOf, type ElementRemoval, type MapRemoval, type RemovalReason } from \"../core/removals.js\";\nimport { compositeMapMethod } from \"./composite.js\";\n\n/** The number of removals that a layer heard from the layers below it, and the number from the first end. */\ninterface Heard {\n all: number;\n first: number;\n}\n\n/**\n * This function gives each removal below `next` to `listener` and counts the removals.\n * With the counts, a layer tells a refused add (the size did not grow) from an add that caused a drop.\n */\nfunction hear<R extends ElementRemoval<unknown> | MapRemoval<unknown, unknown>>(next: object, listener: (removal: R) => void): Heard {\n const heard: Heard = { all: 0, first: 0 };\n removalsOf<R>(next)?.on((removal) => {\n heard.all++;\n if (\"end\" in removal && removal.end === \"first\") heard.first++;\n listener(removal);\n });\n return heard;\n}\n\n/** This function tells if a call added an element: the size grew, after the removals of the layers below. */\nconst added = (size: number, sizeBefore: number, heard: Heard, heardBefore: number): boolean =>\n size - sizeBefore + heard.all - heardBefore > 0;\n\n/**\n * This function gives the removals that change `before` to `after`, in the order of a replay.\n * Each index is the place of the value at the time of its removal. It gives undefined when `after` is not in the order of `before`.\n */\nfunction removalsInOrder<T>(before: readonly T[], after: readonly T[]): { value: T; index: number }[] | undefined {\n const removed: { value: T; index: number }[] = [];\n let kept = 0;\n for (const value of before) {\n if (kept < after.length && Object.is(value, after[kept])) kept++;\n else removed.push({ value, index: kept });\n }\n return kept === after.length ? removed : undefined;\n}\n\n/** This function gives the values of `before` that are not in `after`, with each copy counted. The order does not matter. */\nfunction removedValues<T>(before: readonly T[], after: readonly T[]): T[] {\n const left = new Map<T, number>();\n for (const value of after) left.set(value, (left.get(value) ?? 0) + 1);\n const removed: T[] = [];\n for (const value of before) {\n const count = left.get(value) ?? 0;\n if (count > 0) left.set(value, count - 1);\n else removed.push(value);\n }\n return removed;\n}\n\n/**\n * This function wraps a bulk removal (removeAll, retainAll, removeRange) of the collection below.\n * The base does the removal with its own equality, and `report` gets the contents before and after it.\n */\nfunction bulkRemoval<T>(\n target: { readonly size: number; toArray(): T[] },\n method: Function,\n report: (before: T[], after: T[]) => void,\n): (...args: unknown[]) => unknown {\n return function (...args: unknown[]): unknown {\n const before = target.toArray();\n const result = method.apply(target, args);\n if (target.size !== before.length) report(before, target.toArray());\n return result;\n };\n}\n\n/**\n * This function adds each element with `add` of the layer, one after the other.\n * Thus each element gives its own event, with the rules of a single add. It gives true when one element goes in.\n */\nfunction addEach<T>(elements: Iterable<T>, add: (element: T) => boolean): boolean {\n let changed = false;\n for (const element of Array.from(elements)) {\n if (add(element)) changed = true;\n }\n return changed;\n}\n\n// ============================================================================\n// Event type definitions\n// ============================================================================\n\n/**\n * Events emitted by List collections.\n */\nexport interface ListEvents<T> {\n /** Element was added */\n add: { value: T; index?: number };\n /** Element was removed. A removal by a layer below (a drop) has a `reason`. */\n remove: { value: T; index?: number; reason?: RemovalReason };\n /** Element was replaced */\n set: { oldValue: T; newValue: T; index: number };\n /** Collection was cleared */\n clear: {};\n /** Collection was sorted */\n sort: {};\n /** Collection was reversed */\n reverse: {};\n}\n\n/**\n * Events emitted by Queue collections.\n */\nexport interface QueueEvents<T> {\n /** Element was added to queue */\n enqueue: { value: T };\n /** Element was removed from queue. A removal by a layer below (a drop) has a `reason`. */\n dequeue: { value: T; reason?: RemovalReason };\n /** An element left from a place that is not the head: `remove`, `removeAll` or `retainAll`. */\n remove: { value: T };\n /** Collection was cleared */\n clear: {};\n}\n\n/**\n * Events emitted by Deque collections.\n */\nexport interface DequeEvents<T> {\n /** Element was added to front */\n addFirst: { value: T };\n /** Element was added to back */\n addLast: { value: T };\n /** Element was removed from front. A removal by a layer below (a drop) has a `reason`. */\n removeFirst: { value: T; reason?: RemovalReason };\n /** Element was removed from back. A removal by a layer below (a drop) has a `reason`. */\n removeLast: { value: T; reason?: RemovalReason };\n /** An element left from `index`, not with a method of an end: `remove`, `removeAll` or `retainAll`. */\n remove: { value: T; index: number };\n /** Collection was cleared */\n clear: {};\n}\n\n/**\n * Events emitted by Map collections.\n */\nexport interface MapEvents<K, V> {\n /** Key-value pair was set */\n set: { key: K; value: V; oldValue?: V };\n /** Key was deleted. A removal by a layer below (a drop, an eviction or an expiry) has a `reason`. */\n delete: { key: K; value: V; reason?: RemovalReason };\n /** Collection was cleared */\n clear: {};\n}\n\n/**\n * Generic collection events.\n */\nexport interface CollectionEvents<T> {\n /** Element was added */\n add: { value: T };\n /** Element was removed. A removal by a layer below has a `reason`. */\n remove: { value: T; reason?: RemovalReason };\n /** Collection was cleared */\n clear: {};\n}\n\n// ============================================================================\n// Evented middleware implementations\n// ============================================================================\n\n/**\n * This function makes an evented List middleware.\n *\n * This function emits events for add, remove, set, clear, sort, and reverse operations.\n */\nexport function eventedList<T>(): Middleware<\n List<T>,\n List<T> & {\n on<E extends keyof ListEvents<T>>(\n event: E,\n listener: (payload: ListEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: List<T>) => {\n const emitter = new Emitter<ListEvents<T>>();\n // A removal from the last end left the index that is now the size\n const heard = hear<ElementRemoval<T>>(next, ({ value, end, reason }) =>\n emitter.emit(\"remove\", end === undefined ? { value, reason } : { value, index: end === \"first\" ? 0 : next.size, reason }),\n );\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n // Expose event subscription\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n // A layer below can refuse the element (reject, drop-newest): then no event\n case \"add\":\n case \"push\":\n return function (element: T): any {\n const size = target.size;\n const all = heard.all;\n const result = (value as Function).call(target, element);\n if (added(target.size, size, heard, all)) emitter.emit(\"add\", { value: element });\n return result;\n };\n\n case \"unshift\":\n return function (element: T): void {\n const size = target.size;\n const all = heard.all;\n (value as Function).call(target, element);\n if (added(target.size, size, heard, all)) emitter.emit(\"add\", { value: element, index: 0 });\n };\n\n case \"insert\":\n return function (index: number, element: T): void {\n const size = target.size;\n const all = heard.all;\n const first = heard.first;\n (value as Function).call(target, index, element);\n if (!added(target.size, size, heard, all)) return;\n // A drop of the first element below moved each later index one place lower\n emitter.emit(\"add\", { value: element, index: heard.first > first ? Math.max(0, index - 1) : index });\n };\n\n case \"set\":\n return function (index: number, element: T): T {\n const oldValue = (value as Function).call(target, index, element);\n emitter.emit(\"set\", { oldValue, newValue: element, index });\n return oldValue;\n };\n\n case \"remove\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n emitter.emit(\"remove\", { value: element });\n }\n return result;\n };\n\n case \"removeAt\":\n return function (index: number): T {\n const removed = (value as Function).call(target, index);\n emitter.emit(\"remove\", { value: removed, index });\n return removed;\n };\n\n case \"pop\":\n return function (): T {\n const removed = (value as Function).call(target);\n // The last element had the index that is now the size\n emitter.emit(\"remove\", { value: removed, index: target.size });\n return removed;\n };\n\n case \"shift\":\n return function (): T {\n const removed = (value as Function).call(target);\n emitter.emit(\"remove\", { value: removed, index: 0 });\n return removed;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => {\n const size = target.size;\n const all = heard.all;\n (receiver as List<T>).add(element);\n return added(target.size, size, heard, all);\n });\n };\n\n case \"insertAll\":\n return function (index: number, elements: Iterable<T>): boolean {\n let at = index;\n return addEach(elements, (element) => {\n const size = target.size;\n const all = heard.all;\n const first = heard.first;\n (receiver as List<T>).insert(at, element);\n const wentIn = added(target.size, size, heard, all);\n // A drop of the first element below moved the place one lower. The next element goes after a new one.\n at = Math.min(target.size, Math.max(0, at - (heard.first - first)) + (wentIn ? 1 : 0));\n return wentIn;\n });\n };\n\n case \"removeAll\":\n case \"retainAll\":\n case \"removeRange\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n const removed = removalsInOrder(before, after);\n if (removed) {\n for (const removal of removed) emitter.emit(\"remove\", removal);\n return;\n }\n // A base that changed the order of the rest: a clear and the adds give the same contents\n emitter.emit(\"clear\", {});\n after.forEach((element, at) => emitter.emit(\"add\", { value: element, index: at }));\n });\n\n case \"sort\":\n return function (...args: any[]): void {\n (value as Function).apply(target, args);\n emitter.emit(\"sort\", {});\n };\n\n case \"reverse\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"reverse\", {});\n };\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * This function makes an evented Queue middleware.\n */\nexport function eventedQueue<T>(): Middleware<\n Queue<T>,\n Queue<T> & {\n on<E extends keyof QueueEvents<T>>(\n event: E,\n listener: (payload: QueueEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: Queue<T>) => {\n const emitter = new Emitter<QueueEvents<T>>();\n hear<ElementRemoval<T>>(next, ({ value, reason }) => emitter.emit(\"dequeue\", { value, reason }));\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"offer\":\n case \"enqueue\":\n case \"add\":\n return function (element: T): any {\n const result = (value as Function).call(target, element);\n if (result !== false) {\n emitter.emit(\"enqueue\", { value: element });\n }\n return result;\n };\n\n case \"poll\":\n case \"dequeue\":\n return function (): T {\n const removed = (value as Function).call(target);\n emitter.emit(\"dequeue\", { value: removed });\n return removed;\n };\n\n case \"pollOrUndefined\":\n return function (): T | undefined {\n const size = target.size;\n const removed = (value as Function).call(target);\n if (target.size < size) emitter.emit(\"dequeue\", { value: removed });\n return removed;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => (receiver as Queue<T>).add(element) !== false);\n };\n\n case \"remove\":\n case \"removeAll\":\n case \"retainAll\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n for (const removed of removedValues(before, after)) emitter.emit(\"remove\", { value: removed });\n });\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * This function makes an evented Deque middleware.\n */\nexport function eventedDeque<T>(): Middleware<\n Deque<T>,\n Deque<T> & {\n on<E extends keyof DequeEvents<T>>(\n event: E,\n listener: (payload: DequeEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: Deque<T>) => {\n const emitter = new Emitter<DequeEvents<T>>();\n const heard = hear<ElementRemoval<T>>(next, ({ value, end, reason }) =>\n emitter.emit(end === \"last\" ? \"removeLast\" : \"removeFirst\", { value, reason }),\n );\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n // push of a deque adds at the end (see Deque.push). A layer below can refuse the element.\n case \"addFirst\":\n case \"offerFirst\":\n case \"addLast\":\n case \"offerLast\":\n case \"offer\":\n case \"add\":\n case \"push\":\n return function (element: T): any {\n const size = target.size;\n const all = heard.all;\n const result = (value as Function).call(target, element);\n if (added(target.size, size, heard, all)) {\n emitter.emit(prop === \"addFirst\" || prop === \"offerFirst\" ? \"addFirst\" : \"addLast\", { value: element });\n }\n return result;\n };\n\n case \"removeFirst\":\n case \"pollFirst\":\n case \"poll\":\n case \"dequeue\":\n return function (): T {\n const removed = (value as Function).call(target);\n if (removed !== undefined) {\n emitter.emit(\"removeFirst\", { value: removed });\n }\n return removed;\n };\n\n case \"removeLast\":\n case \"pollLast\":\n case \"pop\":\n return function (): T {\n const removed = (value as Function).call(target);\n if (removed !== undefined) {\n emitter.emit(\"removeLast\", { value: removed });\n }\n return removed;\n };\n\n case \"pollOrUndefined\":\n return function (): T | undefined {\n const size = target.size;\n const removed = (value as Function).call(target);\n if (target.size < size) emitter.emit(\"removeFirst\", { value: removed });\n return removed;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n return addEach(elements, (element) => {\n const size = target.size;\n const all = heard.all;\n (receiver as Deque<T>).addLast(element);\n return added(target.size, size, heard, all);\n });\n };\n\n case \"remove\":\n case \"removeAll\":\n case \"retainAll\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n const removed = removalsInOrder(before, after);\n if (removed) {\n for (const removal of removed) emitter.emit(\"remove\", removal);\n return;\n }\n // A base that changed the order of the rest: a clear and the adds give the same contents\n emitter.emit(\"clear\", {});\n for (const element of after) emitter.emit(\"addLast\", { value: element });\n });\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * This function makes an evented Map middleware.\n */\nexport function eventedMap<K, V>(): Middleware<\n MapLike<K, V>,\n MapLike<K, V> & {\n on<E extends keyof MapEvents<K, V>>(\n event: E,\n listener: (payload: MapEvents<K, V>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: MapLike<K, V>) => {\n const emitter = new Emitter<MapEvents<K, V>>();\n const heard = hear<MapRemoval<K, V>>(next, ({ key, value, reason }) => emitter.emit(\"delete\", { key, value, reason }));\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n // Composite methods (computeIfAbsent, compute, merge, putAll and others) go through this\n // proxy's own set and delete, so each change gives its event (C24). The base calls its own set.\n const composite = compositeMapMethod(receiver as MapLike<K, V>, prop);\n if (composite) {\n return composite;\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"set\":\n return function (key: K, val: V): V | undefined {\n const size = target.size;\n const all = heard.all;\n const oldValue = (value as Function).call(target, key, val);\n // A new key that a layer below refused (reject, drop-newest) gives no event\n if (oldValue !== undefined || added(target.size, size, heard, all)) {\n emitter.emit(\"set\", { key, value: val, oldValue });\n }\n return oldValue;\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n const deletedValue = (value as Function).call(target, key);\n if (deletedValue !== undefined) {\n emitter.emit(\"delete\", { key, value: deletedValue });\n }\n return deletedValue;\n };\n\n // The first or last entry of a navigable map (treeMap)\n case \"pollFirstEntry\":\n case \"pollLastEntry\":\n return function (): Entry<K, V> | undefined {\n const entry: Entry<K, V> | undefined = (value as Function).call(target);\n if (entry !== undefined) emitter.emit(\"delete\", { key: entry.key, value: entry.value });\n return entry;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n\n/**\n * Generic evented collection middleware.\n */\nexport function evented<T>(): Middleware<\n Collection<T>,\n Collection<T> & {\n on<E extends keyof CollectionEvents<T>>(\n event: E,\n listener: (payload: CollectionEvents<T>[E]) => void\n ): Unsubscribe;\n }\n> {\n return (next: Collection<T>) => {\n const emitter = new Emitter<CollectionEvents<T>>();\n hear<ElementRemoval<T>>(next, ({ value, reason }) => emitter.emit(\"remove\", { value, reason }));\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"on\") {\n return emitter.on.bind(emitter);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"add\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n emitter.emit(\"add\", { value: element });\n }\n return result;\n };\n\n case \"remove\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n emitter.emit(\"remove\", { value: element });\n }\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n emitter.emit(\"clear\", {});\n };\n\n // The base writes a bulk change into its storage, and does not call its own add or remove (C24)\n case \"addAll\":\n return function (elements: Iterable<T>): boolean {\n let changed = false;\n for (const element of Array.from(elements)) {\n if ((receiver as Collection<T>).add(element)) changed = true;\n }\n return changed;\n };\n\n case \"removeAll\":\n case \"retainAll\":\n return bulkRemoval<T>(target, value as Function, (before, after) => {\n for (const removed of removedValues(before, after)) emitter.emit(\"remove\", { value: removed });\n });\n\n // The first or last element of a sorted set (treeSet)\n case \"pollFirst\":\n case \"pollLast\":\n return function (): T | undefined {\n const size = target.size;\n const removed = (value as Function).call(target);\n if (target.size < size) emitter.emit(\"remove\", { value: removed });\n return removed;\n };\n }\n }\n\n return value;\n },\n }) as any;\n };\n}\n","/**\n * Synchronized behavior: this module gives thread-safe access with mutex locking.\n *\n * This module wraps collections to serialize all operations using a mutex, making sure that\n * thread-safe access in concurrent environments. Mirrors Java's\n * Collections.synchronizedList() and related methods.\n *\n * Note: JavaScript is single-threaded, but async operations can interleave.\n * This middleware makes sure that atomic operations across async boundaries.\n *\n * @example\n * const list = compose(\n * synchronized()\n * )(arrayList<number>())\n *\n * // All operations are now serialized\n * await Promise.all([\n * list.add(1),\n * list.add(2),\n * list.add(3)\n * ])\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\n\n/**\n * Simple mutex implementation for JavaScript async operations.\n *\n * This middleware makes sure that only one operation starts at a time, even if\n * multiple async operations are started concurrently.\n */\n/** True for an `async` function or method. */\nfunction isAsyncFunction(value: unknown): boolean {\n return typeof value === \"function\" && (value as { [Symbol.toStringTag]?: string })[Symbol.toStringTag] === \"AsyncFunction\";\n}\n\nclass Mutex {\n private queue: Promise<void> = Promise.resolve();\n\n /**\n * This method acquires the lock and starts the function.\n * Other operations wait until this completes.\n */\n async lock<T>(fn: () => T | Promise<T>): Promise<T> {\n const run = this.queue.then(() => fn());\n this.queue = run.then(\n () => undefined,\n () => undefined\n );\n return run;\n }\n\n /**\n * Synchronous version that starts immediately.\n * Still queues to prevent interleaving with async operations.\n */\n\n}\n\n/**\n * This function makes a synchronized middleware that locks all method calls.\n *\n * Every method call on the collection is wrapped with a mutex,\n * making sure that atomic execution even in concurrent async scenarios.\n *\n * @example\n * const syncList = compose(\n * synchronized()\n * )(arrayList<number>())\n *\n * // These additions are guaranteed to execute in order\n * await Promise.all([\n * syncList.add(1),\n * syncList.add(2),\n * syncList.add(3)\n * ])\n */\nexport function synchronized<C extends object>(): Middleware<C> {\n return (next: C): C => {\n const mutex = new Mutex();\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Don't wrap non-functions\n if (typeof value !== \"function\") {\n return value;\n }\n\n // An async method runs inside the lock: it starts after the earlier async calls end.\n // (Before, every method ran first and took the lock after, so nothing was excluded:\n // BUGS-2026-07 L11.) A plain method runs at once: JavaScript does not interrupt it.\n // When a plain method returns a promise anyway, the lock waits for that promise.\n if (isAsyncFunction(value)) {\n return function (this: unknown, ...args: unknown[]) {\n return mutex.lock(() => (value as Function).apply(target, args));\n };\n }\n return function (this: unknown, ...args: unknown[]) {\n const result = (value as Function).apply(target, args);\n if (result instanceof Promise) {\n return mutex.lock(() => result);\n }\n return result;\n };\n },\n }) as C;\n };\n}\n\n/**\n * Alias for Java compatibility: synchronizedList\n */\nexport const synchronizedList : typeof synchronized = synchronized;\n\n/**\n * Alias for Java compatibility: synchronizedMap\n */\nexport const synchronizedMap : typeof synchronized = synchronized;\n\n/**\n * Alias for Java compatibility: synchronizedCollection\n */\nexport const synchronizedCollection : typeof synchronized = synchronized;\n\n/**\n * Alias for Java compatibility: synchronizedSet\n */\nexport const synchronizedSet : typeof synchronized = synchronized;\n\n/**\n * Advanced synchronized middleware with reentrant locking.\n *\n * With this function, the same \"thread\" (async context) can acquire the lock multiple times.\n * Useful for methods that call other synchronized methods internally.\n *\n * Note: JavaScript has no true thread IDs. This function uses async context\n * tracking if available. If not, the behavior is non-reentrant.\n */\nexport function reentrantSynchronized<C extends object>(): Middleware<C> {\n return (next: C): C => {\n const mutex = new Mutex();\n let lockHolder: symbol | null = null;\n let lockCount = 0;\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n return async function (this: any, ...args: any[]) {\n // Generate a unique ID for this call context\n const callerId = Symbol(\"caller\");\n\n // If we already hold the lock, execute directly (reentrant)\n if (lockHolder === callerId) {\n lockCount++;\n try {\n const result = (value as Function).apply(target, args);\n return result instanceof Promise ? await result : result;\n } finally {\n lockCount--;\n }\n }\n\n // Otherwise, acquire the lock\n return mutex.lock(async () => {\n lockHolder = callerId;\n lockCount = 1;\n try {\n const result = (value as Function).apply(target, args);\n return result instanceof Promise ? await result : result;\n } finally {\n lockCount--;\n if (lockCount === 0) {\n lockHolder = null;\n }\n }\n });\n };\n },\n }) as C;\n };\n}\n\n/**\n * Read-write lock implementation for collections.\n *\n * With this function, multiple concurrent readers can read, but a writer is exclusive.\n * More efficient than full synchronization for read-heavy workloads.\n *\n * @example\n * const list = compose(\n * readWriteLock()\n * )(arrayList<number>())\n *\n * // Multiple reads can happen concurrently\n * await Promise.all([\n * list.get(0),\n * list.get(1),\n * list.get(2)\n * ])\n */\nexport function readWriteLock<C extends object>(): Middleware<C> {\n return (next: C): C => {\n let readers = 0;\n let writer = false;\n let waitingReaders: (() => void)[] = [];\n let waitingWriters: (() => void)[] = [];\n\n // Hand-off rule: the releaser counts the waiters it wakes (readers += n, or writer = true),\n // so a woken waiter does not count itself again. (Before, releaseWrite set readers = n and\n // each woken reader added 1, so the count never came back to 0 and writers waited forever:\n // BUGS-2026-07 L11.)\n const acquireRead = async (): Promise<void> => {\n if (writer || waitingWriters.length > 0) {\n await new Promise<void>((resolve) => waitingReaders.push(resolve));\n return;\n }\n readers++;\n };\n\n const releaseRead = (): void => {\n readers--;\n if (readers === 0 && waitingWriters.length > 0) {\n writer = true;\n const next = waitingWriters.shift()!;\n next();\n }\n };\n\n const acquireWrite = async (): Promise<void> => {\n if (writer || readers > 0) {\n await new Promise<void>((resolve) => waitingWriters.push(resolve));\n return;\n }\n writer = true;\n };\n\n const releaseWrite = (): void => {\n writer = false;\n if (waitingWriters.length > 0) {\n writer = true;\n const next = waitingWriters.shift()!;\n next();\n } else if (waitingReaders.length > 0) {\n const allReaders = waitingReaders.splice(0);\n readers += allReaders.length;\n allReaders.forEach((resolve) => resolve());\n }\n };\n\n // Methods that only read (don't mutate)\n const READ_METHODS = new Set([\n \"get\",\n \"has\",\n \"contains\",\n \"containsAll\",\n \"containsValue\",\n \"indexOf\",\n \"lastIndexOf\",\n \"peek\",\n \"peekFirst\",\n \"peekLast\",\n \"first\",\n \"last\",\n \"isEmpty\",\n \"size\",\n \"toArray\",\n \"keys\",\n \"values\",\n \"entries\",\n \"forEach\",\n \"getOrDefault\",\n \"getOrUndefined\",\n \"descendingIterator\",\n ]);\n\n // The reads that give an iterator. The lock copies the elements before it releases the read (C32).\n const ITERATOR_READS = new Set([\"keys\", \"values\", \"entries\", \"descendingIterator\"]);\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n // A method with a symbol key, for example Symbol.iterator, stays synchronous, so `for of` works (C32).\n // The loop reads at once with no lock, as a plain method of synchronized().\n if (typeof prop === \"symbol\") {\n return function (this: unknown, ...args: unknown[]) {\n return (value as Function).apply(target, args);\n };\n }\n\n const isReadMethod = READ_METHODS.has(prop);\n const isIteratorRead = ITERATOR_READS.has(prop);\n\n return async function (this: any, ...args: any[]) {\n if (isReadMethod) {\n // Acquire read lock\n await acquireRead();\n try {\n const raw = (value as Function).apply(target, args);\n const result = raw instanceof Promise ? await raw : raw;\n // Before C32, the iteration started after the release of the read, so a write could change the elements.\n return isIteratorRead && result != null && typeof result[Symbol.iterator] === \"function\"\n ? Array.from(result as Iterable<unknown>)[Symbol.iterator]()\n : result;\n } finally {\n releaseRead();\n }\n } else {\n // Acquire write lock\n await acquireWrite();\n try {\n const result = (value as Function).apply(target, args);\n return result instanceof Promise ? await result : result;\n } finally {\n releaseWrite();\n }\n }\n };\n },\n }) as C;\n };\n}\n","/**\n * LRU (Least Recently Used) eviction behavior.\n *\n * This module tracks access times and automatically evicts the least recently used\n * elements when capacity is reached. Perfect for caching.\n *\n * @example\n * const cache = compose(\n * lruMap<string, Data>({ capacity: 100 })\n * )(hashMap<string, Data>())\n *\n * cache.set('key1', data1) // Accessed\n * cache.get('key1') // Accessed again (moves to front)\n * // When full, least recently accessed keys are evicted\n */\n\nimport { checkCapacity } from \"../core/capacity.js\";\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { compositeMapMethod } from \"./composite.js\";\nimport { removals, removalSource, type MapRemoval } from \"../core/removals.js\";\n\n/**\n * Options for LRU behavior.\n */\nexport interface LRUOptions {\n /**\n * The maximum number of entries, a positive whole number. When the map is full, a new key\n * evicts the least recently used entry.\n */\n capacity: number;\n\n /**\n * Optional callback invoked when an item is evicted.\n */\n onEvict?: (info: { key: any; value: any; timestamp: number }) => void;\n}\n\n/**\n * Metadata for tracking LRU access.\n */\ninterface LRUNode<K, V> {\n key: K;\n value: V;\n lastAccessed: number;\n prev: LRUNode<K, V> | null;\n next: LRUNode<K, V> | null;\n}\n\n/**\n * This function makes an LRU Map middleware.\n *\n * This function maintains a doubly-linked list to track access order.\n * Most recently accessed items are at the head.\n * When capacity is exceeded, items at the tail are evicted.\n *\n * @throws RangeError when `options.capacity` is not a positive whole number.\n */\nexport function lruMap<K, V>(\n options: LRUOptions\n): Middleware<MapLike<K, V>, MapLike<K, V> & { readonly isFull: boolean }> {\n const { onEvict } = options;\n const capacity = checkCapacity(options.capacity, \"lruMap\");\n\n return (next: MapLike<K, V>): MapLike<K, V> & { readonly isFull: boolean } => {\n // Doubly-linked list for LRU tracking\n let head: LRUNode<K, V> | null = null;\n let tail: LRUNode<K, V> | null = null;\n const nodeMap = new Map<K, LRUNode<K, V>>();\n\n const moveToHead = (node: LRUNode<K, V>): void => {\n // Remove from current position\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n tail = node.prev;\n }\n\n // Add to head\n node.prev = null;\n node.next = head;\n if (head) {\n head.prev = node;\n }\n head = node;\n\n if (!tail) {\n tail = node;\n }\n\n node.lastAccessed = Date.now();\n };\n\n const addNode = (key: K, value: V): void => {\n const node: LRUNode<K, V> = {\n key,\n value,\n lastAccessed: Date.now(),\n prev: null,\n next: head,\n };\n\n if (head) {\n head.prev = node;\n }\n head = node;\n\n if (!tail) {\n tail = node;\n }\n\n nodeMap.set(key, node);\n };\n\n const removeNode = (node: LRUNode<K, V>): void => {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n tail = node.prev;\n }\n\n nodeMap.delete(node.key);\n };\n\n // A removal below (for example an expiry of ttlMap, in compose(lruMap, ttlMap)) removes the node of its key\n const source = removalSource<MapRemoval<K, V>>(next, ({ key }) => {\n const node = nodeMap.get(key);\n if (node) removeNode(node);\n });\n\n // A layer below with no removal channel can remove an entry without this layer seeing it. Its node is\n // then stale: the list must not keep it (it holds the value, and it would grow without bound) and evicting\n // it is not an eviction. With the channel, no node is stale and these checks find nothing.\n const dropStaleNodes = (): void => {\n for (const node of [...nodeMap.values()]) {\n if (!next.has(node.key)) {\n removeNode(node);\n }\n }\n };\n\n const evictLRU = (): void => {\n while (tail) {\n const candidate = tail;\n removeNode(candidate);\n if (!next.has(candidate.key)) {\n // Already removed below: skip it and evict the next least recently used entry\n continue;\n }\n next.delete(candidate.key);\n\n if (onEvict) {\n onEvict({\n key: candidate.key,\n value: candidate.value,\n timestamp: candidate.lastAccessed,\n });\n }\n source.emit({ key: candidate.key, value: candidate.value, reason: \"evict\" });\n return;\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === removals) {\n return source.channel;\n }\n // Add isFull property\n if (prop === \"isFull\") {\n return target.size >= capacity;\n }\n\n // Composite methods (setIfAbsent, compute, merge, putAll and others) go through this\n // proxy's own primitives, so they keep this behavior's rules (BUGS-2026-07 L13)\n const composite = compositeMapMethod(receiver as MapLike<K, V>, prop);\n if (composite) {\n return composite;\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"get\":\n return function (key: K): V {\n const result: V = (value as Function).call(target, key);\n // Update access time\n const node = nodeMap.get(key);\n if (node) {\n moveToHead(node);\n }\n return result;\n };\n\n case \"has\":\n return function (key: K): boolean {\n const result = (value as Function).call(target, key);\n const node = nodeMap.get(key);\n if (node && result) {\n // Update access time\n moveToHead(node);\n }\n return result;\n };\n\n case \"set\":\n return function (key: K, val: V): V | undefined {\n const hadKey = target.has(key);\n\n if (hadKey) {\n // Update existing\n const oldValue = (value as Function).call(target, key, val);\n const node = nodeMap.get(key);\n if (node) {\n node.value = val;\n moveToHead(node);\n }\n return oldValue;\n } else {\n // Add new. A stale node for this key (its entry was removed below) must not\n // stay in the list: evicting it later would delete the new node's map entry.\n const stale = nodeMap.get(key);\n if (stale) {\n removeNode(stale);\n }\n // Keep the node list bounded. At most `capacity` nodes are live, so at twice the capacity a scan\n // removes at least `capacity` stale nodes: the cost of a set is amortized O(1). A scan at the\n // capacity read each node at each set into a full map (C10). evictLRU skips the other stale nodes.\n if (nodeMap.size >= 2 * capacity) {\n dropStaleNodes();\n }\n if (target.size >= capacity) {\n evictLRU();\n }\n const result = (value as Function).call(target, key, val);\n addNode(key, val);\n return result;\n }\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n const result = (value as Function).call(target, key);\n const node = nodeMap.get(key);\n if (node) {\n removeNode(node);\n }\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n head = null;\n tail = null;\n nodeMap.clear();\n };\n }\n }\n\n return value;\n },\n }) as MapLike<K, V> & { readonly isFull: boolean };\n };\n}\n\n/**\n * This class makes an LRU cache with a simpler API.\n * This is a standalone LRU cache implementation.\n *\n * @example\n * const cache = lruCache<string, Data>(100)\n * cache.set('key', value)\n * cache.get('key') // Moves to front\n */\nexport class LRUCache<K, V> {\n private readonly capacity: number;\n private readonly onEvict: ((key: K, value: V) => void) | undefined;\n private map: Map<K, { value: V; node: LRUNode<K, V> }> = new Map();\n private head: LRUNode<K, V> | null = null;\n private tail: LRUNode<K, V> | null = null;\n\n /**\n * @param capacity - The maximum number of entries, a positive whole number.\n * @param onEvict - The function that this cache starts for each entry that it evicts.\n * @throws RangeError when `capacity` is not a positive whole number.\n */\n constructor(capacity: number, onEvict?: ((key: K, value: V) => void) | undefined) {\n this.capacity = checkCapacity(capacity, \"LRUCache\");\n this.onEvict = onEvict;\n }\n\n get size(): number {\n return this.map.size;\n }\n\n get isFull(): boolean {\n return this.map.size >= this.capacity;\n }\n\n get(key: K): V | undefined {\n const entry = this.map.get(key);\n if (!entry) return undefined;\n\n this.moveToHead(entry.node);\n return entry.value;\n }\n\n set(key: K, value: V): void {\n const entry = this.map.get(key);\n\n if (entry) {\n // Update existing\n entry.value = value;\n entry.node.value = value;\n this.moveToHead(entry.node);\n } else {\n // Add new\n if (this.map.size >= this.capacity) {\n this.evictLRU();\n }\n\n const node: LRUNode<K, V> = {\n key,\n value,\n lastAccessed: Date.now(),\n prev: null,\n next: this.head,\n };\n\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n\n if (!this.tail) {\n this.tail = node;\n }\n\n this.map.set(key, { value, node });\n }\n }\n\n has(key: K): boolean {\n return this.map.has(key);\n }\n\n delete(key: K): boolean {\n const entry = this.map.get(key);\n if (!entry) return false;\n\n this.removeNode(entry.node);\n this.map.delete(key);\n return true;\n }\n\n /**\n * This method deletes each entry for which `matches` gives true, and it gives the number of\n * deleted entries. It is not a use: the order of the other entries does not change, and it\n * does not start `onEvict`. It starts `matches` once for each entry, the most recent first. If\n * `matches` throws, the entries that it matched before stay deleted.\n *\n * @param matches - The test of an entry.\n * @returns The number of deleted entries.\n */\n deleteWhere(matches: (value: V, key: K) => boolean): number {\n const nodes: LRUNode<K, V>[] = [];\n for (let node = this.head; node; node = node.next) nodes.push(node);\n let deleted = 0;\n for (const node of nodes) {\n // The function `matches` can change the cache. Skip each node that is not in it now.\n if (this.map.get(node.key)?.node !== node) continue;\n if (!matches(node.value, node.key)) continue;\n // The function `matches` can delete this node itself, so check again.\n if (this.map.get(node.key)?.node !== node) continue;\n this.removeNode(node);\n this.map.delete(node.key);\n deleted++;\n }\n return deleted;\n }\n\n clear(): void {\n this.map.clear();\n this.head = null;\n this.tail = null;\n }\n\n private moveToHead(node: LRUNode<K, V>): void {\n if (node === this.head) return;\n\n // Remove from current position\n if (node.prev) {\n node.prev.next = node.next;\n }\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n\n // Add to head\n node.prev = null;\n node.next = this.head;\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n\n node.lastAccessed = Date.now();\n }\n\n private removeNode(node: LRUNode<K, V>): void {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this.head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n }\n\n private evictLRU(): void {\n if (!this.tail) return;\n\n const evicted = this.tail;\n this.removeNode(evicted);\n this.map.delete(evicted.key);\n\n if (this.onEvict) {\n this.onEvict(evicted.key, evicted.value);\n }\n }\n\n /**\n * This method gives keys in LRU order (most recent first).\n */\n *keys(): IterableIterator<K> {\n let node = this.head;\n while (node) {\n yield node.key;\n node = node.next;\n }\n }\n\n /**\n * This method gives entries in LRU order (most recent first).\n */\n *entries(): IterableIterator<[K, V]> {\n let node = this.head;\n while (node) {\n yield [node.key, node.value];\n node = node.next;\n }\n }\n}\n\n/**\n * This function makes an LRU cache.\n *\n * @throws RangeError when `capacity` is not a positive whole number.\n */\nexport function lruCache<K, V>(\n capacity: number,\n onEvict?: (key: K, value: V) => void\n): LRUCache<K, V> {\n return new LRUCache(capacity, onEvict);\n}\n","/**\n * TTL (Time-To-Live) expiration behavior.\n *\n * The behavior removes each element when its time to live ends.\n * Perfect for temporary caches and time-limited data.\n *\n * @example\n * const cache = compose(\n * ttlMap<string, Data>({ ttl: 60000 }) // 60 seconds\n * )(hashMap<string, Data>())\n *\n * cache.set('key', data)\n * // After 60 seconds, 'key' is automatically removed\n */\n\nimport type { Middleware } from \"../core/middleware.js\";\nimport type { Entry, MapLike } from \"../interfaces/map.js\";\nimport { compositeMapMethod } from \"./composite.js\";\nimport { removals, removalSource, type ElementRemoval, type MapRemoval } from \"../core/removals.js\";\nimport type { Collection } from \"../interfaces/collection.js\";\n\n/**\n * This function starts the background expiration checker, and it does not keep a Node.js process alive.\n * (In a browser, setInterval gives a number and there is nothing to unref.)\n */\nfunction startExpirationTimer(check: () => void, interval: number): ReturnType<typeof setInterval> {\n const timer = setInterval(check, interval);\n (timer as unknown as { unref?: () => void }).unref?.();\n return timer;\n}\n\n/**\n * Options for TTL behavior.\n */\nexport interface TTLOptions {\n /**\n * Time-to-live in milliseconds.\n * Elements expire after this duration.\n */\n ttl: number;\n\n /**\n * Interval for checking expired elements (in milliseconds).\n * @default 1000 (check every second)\n */\n checkInterval?: number;\n\n /**\n * Optional callback invoked when an element expires.\n */\n onExpire?: (info: { key: any; value: any; createdAt: number; expiredAt: number }) => void;\n}\n\n/**\n * Metadata for TTL tracking.\n */\ninterface TTLEntry<V> {\n value: V;\n expiresAt: number;\n createdAt: number;\n}\n\n/**\n * This function makes a TTL Map middleware.\n *\n * An entry is live while the time is less than the time of its last `set` plus `ttl`.\n * Each access to the map first removes the expired entries, so each read shows only live entries.\n * The layer gives each expired entry to `onExpire` one time, in the order of expiry.\n * A background interval also removes expired entries, so `onExpire` occurs with no access.\n *\n * The layer keeps the times in the order of expiry, so the removal before an access is amortized O(1).\n * This order needs a clock that does not go back. If `Date.now()` goes back, an entry can stay until the entries before it expire.\n */\nexport function ttlMap<K, V>(\n options: TTLOptions\n): Middleware<MapLike<K, V>, MapLike<K, V> & { readonly dispose: () => void }> {\n const { ttl, checkInterval = 1000, onExpire } = options;\n\n return (\n next: MapLike<K, V>\n ): MapLike<K, V> & { readonly dispose: () => void } => {\n // The times of the live keys, in the order of expiry: a set deletes its key before it adds it again\n const metadata = new Map<K, TTLEntry<V>>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n // A removal below (for example an eviction of lruMap) ends the time of its key, so it never expires\n const source = removalSource<MapRemoval<K, V>>(next, ({ key }) => void metadata.delete(key));\n\n // This function removes the expired entries from the front of the order, and stops at the first live entry\n const sweep = (): void => {\n const now = Date.now();\n for (const [key, entry] of metadata) {\n if (now < entry.expiresAt) return;\n metadata.delete(key);\n next.delete(key);\n onExpire?.({ key, value: entry.value, createdAt: entry.createdAt, expiredAt: now });\n source.emit({ key, value: entry.value, reason: \"expire\" });\n }\n };\n\n intervalId = startExpirationTimer(sweep, checkInterval);\n\n const dispose = (): void => {\n if (intervalId) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"dispose\") {\n return dispose;\n }\n if (prop === removals) {\n return source.channel;\n }\n\n // Composite methods (setIfAbsent, compute, merge, putAll and others) go through this\n // proxy's own primitives, so they keep the expiry rules (BUGS-2026-07 L13)\n const composite = compositeMapMethod(receiver as MapLike<K, V>, prop);\n if (composite) {\n return composite;\n }\n\n // A getter (size, isEmpty) reads only live entries\n sweep();\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== \"function\") {\n return value;\n }\n\n switch (prop) {\n case \"set\":\n return function (key: K, val: V): V | undefined {\n sweep();\n const result = (value as Function).call(target, key, val);\n const now = Date.now();\n metadata.delete(key);\n metadata.set(key, { value: val, expiresAt: now + ttl, createdAt: now });\n return result;\n };\n\n case \"delete\":\n return function (key: K): V | undefined {\n sweep();\n metadata.delete(key);\n return (value as Function).call(target, key);\n };\n\n case \"clear\":\n return function (): void {\n metadata.clear();\n (value as Function).call(target);\n };\n\n // The iteration gives the entries that are live when it starts. A removal while it runs (by a read in\n // the loop, or by the interval between the steps of an async loop) does not change it, so the base\n // iterator never sees a change and never throws.\n case Symbol.iterator:\n case \"entries\":\n return function (): IterableIterator<Entry<K, V>> {\n sweep();\n return Array.from(target as Iterable<Entry<K, V>>).values();\n };\n\n case \"keys\":\n return function (): IterableIterator<K> {\n sweep();\n return Array.from(target as Iterable<Entry<K, V>>, (e) => e.key).values();\n };\n\n case \"values\":\n return function (): IterableIterator<V> {\n sweep();\n return Array.from(target as Iterable<Entry<K, V>>, (e) => e.value).values();\n };\n\n case \"forEach\":\n return function (callback: (value: V, key: K, map: MapLike<K, V>) => void): void {\n sweep();\n for (const e of Array.from(target as Iterable<Entry<K, V>>)) callback(e.value, e.key, receiver as MapLike<K, V>);\n };\n\n default:\n // Each other method (get, has, getOrUndefined, the iteration) reads only live entries,\n // also when a caller keeps the method and calls it later\n return function (this: unknown, ...args: unknown[]): unknown {\n sweep();\n return (value as Function).apply(target, args);\n };\n }\n },\n }) as MapLike<K, V> & { readonly dispose: () => void };\n };\n}\n\n/**\n * This function makes a TTL Collection middleware.\n *\n * Note: This is less precise than TTL map because collections don't have keys.\n * Elements are tracked by reference, which can fail for primitive types.\n */\nexport function ttlCollection<T>(\n options: Omit<TTLOptions, \"onExpire\"> & {\n onExpire?: (info: { element: T; createdAt: number; expiredAt: number }) => void;\n }\n): Middleware<Collection<T>, Collection<T> & { readonly dispose: () => void }> {\n const { ttl, checkInterval = 1000, onExpire } = options;\n\n return (\n next: Collection<T>\n ): Collection<T> & { readonly dispose: () => void } => {\n const metadata = new Map<T, { expiresAt: number; createdAt: number }>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const source = removalSource<ElementRemoval<T>>(next, ({ value }) => void metadata.delete(value));\n\n const checkExpired = (): void => {\n const now = Date.now();\n const expired: T[] = [];\n\n for (const [element, entry] of metadata) {\n if (now >= entry.expiresAt) {\n expired.push(element);\n }\n }\n\n for (const element of expired) {\n const entry = metadata.get(element);\n if (entry) {\n next.remove(element);\n metadata.delete(element);\n\n if (onExpire) {\n onExpire({\n element,\n createdAt: entry.createdAt,\n expiredAt: now,\n });\n }\n source.emit({ value: element, reason: \"expire\" });\n }\n }\n };\n\n intervalId = startExpirationTimer(checkExpired, checkInterval);\n\n const dispose = (): void => {\n if (intervalId) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n return new Proxy(next, {\n get(target, prop, receiver) {\n if (prop === \"dispose\") {\n return dispose;\n }\n if (prop === removals) {\n return source.channel;\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n switch (prop) {\n case \"add\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n const now = Date.now();\n metadata.set(element, {\n expiresAt: now + ttl,\n createdAt: now,\n });\n }\n return result;\n };\n\n case \"remove\":\n return function (element: T): boolean {\n const result = (value as Function).call(target, element);\n if (result) {\n metadata.delete(element);\n }\n return result;\n };\n\n case \"clear\":\n return function (): void {\n (value as Function).call(target);\n metadata.clear();\n };\n }\n }\n\n return value;\n },\n }) as Collection<T> & { readonly dispose: () => void };\n };\n}\n\n/**\n * Standalone TTL cache with Map-like API.\n *\n * @example\n * const cache = new TTLCache<string, number>(60000) // 60 second TTL\n * cache.set('key', 42)\n * setTimeout(() => {\n * cache.get('key') // undefined (expired)\n * }, 61000)\n */\nexport class TTLCache<K, V> {\n private readonly ttl: number;\n private readonly checkInterval: number;\n private readonly onExpire: ((key: K, value: V) => void) | undefined;\n private map = new Map<K, TTLEntry<V>>();\n private intervalId: ReturnType<typeof setInterval> | null = null;\n\n constructor(ttl: number, checkInterval: number = 1000, onExpire?: ((key: K, value: V) => void) | undefined) {\n this.ttl = ttl;\n this.checkInterval = checkInterval;\n this.onExpire = onExpire;\n this.startExpirationCheck();\n }\n\n get size(): number {\n this.cleanup();\n return this.map.size;\n }\n\n get(key: K): V | undefined {\n const entry = this.map.get(key);\n if (!entry) return undefined;\n\n if (Date.now() >= entry.expiresAt) {\n this.map.delete(key);\n if (this.onExpire) {\n this.onExpire(key, entry.value);\n }\n return undefined;\n }\n\n return entry.value;\n }\n\n set(key: K, value: V, customTTL?: number): void {\n const now = Date.now();\n const ttlToUse = customTTL !== undefined ? customTTL : this.ttl;\n\n this.map.set(key, {\n value,\n expiresAt: now + ttlToUse,\n createdAt: now,\n });\n }\n\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n delete(key: K): boolean {\n return this.map.delete(key);\n }\n\n clear(): void {\n this.map.clear();\n }\n\n /**\n * This method removes the expired entries at once.\n */\n cleanup(): void {\n const now = Date.now();\n const expired: K[] = [];\n\n for (const [key, entry] of this.map) {\n if (now >= entry.expiresAt) {\n expired.push(key);\n }\n }\n\n for (const key of expired) {\n const entry = this.map.get(key);\n if (entry) {\n this.map.delete(key);\n if (this.onExpire) {\n this.onExpire(key, entry.value);\n }\n }\n }\n }\n\n /**\n * This method gives the remaining TTL of a key, in milliseconds.\n * This method gives undefined if key doesn't exist or is expired.\n */\n getTTL(key: K): number | undefined {\n const entry = this.map.get(key);\n if (!entry) return undefined;\n\n const remaining = entry.expiresAt - Date.now();\n return remaining > 0 ? remaining : undefined;\n }\n\n /**\n * This method updates the TTL of a key that is in the map.\n */\n touch(key: K, customTTL?: number): boolean {\n const entry = this.map.get(key);\n if (!entry) return false;\n\n if (Date.now() >= entry.expiresAt) {\n this.map.delete(key);\n return false;\n }\n\n const ttlToUse = customTTL !== undefined ? customTTL : this.ttl;\n entry.expiresAt = Date.now() + ttlToUse;\n return true;\n }\n\n private startExpirationCheck(): void {\n this.intervalId = startExpirationTimer(() => this.cleanup(), this.checkInterval);\n }\n\n /**\n * This method stops the background expiration checker and cleans up.\n */\n dispose(): void {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n }\n\n *keys(): IterableIterator<K> {\n this.cleanup();\n yield* this.map.keys();\n }\n\n *values(): IterableIterator<V> {\n this.cleanup();\n for (const entry of this.map.values()) {\n yield entry.value;\n }\n }\n\n *entries(): IterableIterator<[K, V]> {\n this.cleanup();\n for (const [key, entry] of this.map) {\n yield [key, entry.value];\n }\n }\n}\n\n/**\n * Factory function to make a TTL cache.\n */\nexport function ttlCache<K, V>(\n ttl: number,\n options?: {\n checkInterval?: number;\n onExpire?: (key: K, value: V) => void;\n }\n): TTLCache<K, V> {\n return new TTLCache(\n ttl,\n options?.checkInterval,\n options?.onExpire\n );\n}\n","/**\n * AsyncQueue - An async iterable queue with backpressure support.\n *\n * The queue is for producer-consumer patterns where producers can wait when\n * the queue is full and consumers can wait when the queue is empty.\n * This module implements AsyncIterable for use with for-await-of loops.\n *\n * @example\n * const queue = asyncQueue<number>({ capacity: 10 })\n *\n * // Producer\n * await queue.put(42) // Waits if queue is full\n *\n * // Consumer\n * const value = await queue.take() // Waits if queue is empty\n *\n * // Async iteration\n * for await (const value of queue) {\n * console.log(value)\n * }\n */\n\nimport type { AsyncQueue as IAsyncQueue } from \"../interfaces/queue.js\";\n\n/** The text of the error of a put, a new one or a waiting one, on a closed queue. */\nconst CLOSED = \"Queue is closed\";\n\n/** The text of the error of a take, a peek or a wait on a queue that is closed and empty. */\nconst CLOSED_AND_EMPTY = \"Queue is closed and empty\";\n\n/**\n * Options for making an AsyncQueue.\n */\nexport interface AsyncQueueOptions {\n /**\n * The maximum number of elements: a whole number of 0 or more, or `Infinity` for no bound.\n * Any other value gives a `RangeError`.\n * @default Infinity\n */\n capacity?: number;\n\n /**\n * Timeout for put/take operations in milliseconds.\n * @default undefined (no timeout)\n */\n timeout?: number;\n}\n\n/**\n * Resolver for waiting operations.\n */\ninterface Resolver<T> {\n resolve: (value: T) => void;\n reject: (reason: any) => void;\n timeoutId?: ReturnType<typeof setTimeout>;\n}\n\n/** A waiting put: it keeps its element until the queue takes it. */\ninterface Putter<T> extends Resolver<void> {\n element: T;\n}\n\n/**\n * AsyncQueue<T> - Thread-safe async queue with backpressure.\n *\n * Features:\n * - Blocking put() when full (backpressure)\n * - Blocking take() when empty\n * - AsyncIterable support\n * - Graceful closing\n * - Timeouts\n *\n * Perfect for:\n * - Producer-consumer patterns\n * - Rate limiting\n * - Task queues\n * - Stream processing\n */\nexport class AsyncQueue<T> implements IAsyncQueue<T> {\n private buffer: T[] = [];\n private putters: Putter<T>[] = [];\n private takers: Resolver<T>[] = [];\n /** The calls of `peek` that wait: they see the next element, but they do not take it. */\n private peekers: Resolver<T>[] = [];\n private _isClosed = false;\n private readonly capacity: number;\n private readonly defaultTimeout?: number;\n\n constructor(options: AsyncQueueOptions = {}) {\n const capacity = options.capacity ?? Infinity;\n // A capacity of -1, 1.5 or NaN gave a wrong remainingCapacity, or each put waited with no end.\n if (capacity !== Infinity && !(Number.isInteger(capacity) && capacity >= 0)) {\n throw new RangeError(`The capacity must be a whole number of 0 or more, or Infinity: ${String(capacity)}`);\n }\n this.capacity = capacity;\n if (options.timeout !== undefined) {\n this.defaultTimeout = options.timeout;\n }\n }\n\n // ========================================================================\n // Size and state\n // ========================================================================\n\n get size(): number {\n return this.buffer.length;\n }\n\n get isEmpty(): boolean {\n return this.buffer.length === 0;\n }\n\n get isFull(): boolean {\n return this.buffer.length >= this.capacity;\n }\n\n get isClosed(): boolean {\n return this._isClosed;\n }\n\n get remainingCapacity(): number {\n return this.capacity === Infinity ? Infinity : this.capacity - this.buffer.length;\n }\n\n // ========================================================================\n // Blocking operations\n // ========================================================================\n\n /**\n * This method adds an element to the queue.\n * If the queue is full, waits until space is available. With a capacity of 0, it waits until\n * a taker takes the element (a rendezvous).\n *\n * @throws Error if queue is closed\n * @throws Error if timeout expires\n */\n async put(element: T, timeout?: number): Promise<void> {\n if (this._isClosed) {\n throw new Error(CLOSED);\n }\n if (this.tryPutNow(element)) {\n return;\n }\n\n // A waiting peek sees the element of a waiting put (a capacity of 0)\n this.wakePeekers(element);\n\n // Queue is full: wait with the element. (Before, a waiting putter kept only its resolve\n // function, so its element was dropped when space came: BUGS-2026-07 C11.)\n return new Promise<void>((resolve, reject) => {\n const putter: Putter<T> = { element, resolve, reject };\n const timeoutMs = timeout ?? this.defaultTimeout;\n if (timeoutMs !== undefined) {\n putter.timeoutId = setTimeout(() => {\n const index = this.putters.indexOf(putter);\n if (index !== -1) {\n this.putters.splice(index, 1);\n }\n reject(new Error(`Put timeout after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n this.putters.push(putter);\n });\n }\n\n /**\n * This method removes an element from the queue and gives it.\n * If the queue is empty, waits until an element is available.\n *\n * @throws Error if queue is closed and empty\n * @throws Error if timeout expires\n */\n async take(timeout?: number): Promise<T> {\n const next = this.takeNow();\n if (next.found) {\n return next.element;\n }\n\n // If closed and empty, throw\n if (this._isClosed) {\n throw new Error(CLOSED_AND_EMPTY);\n }\n\n // Wait for an element\n return new Promise<T>((resolve, reject) => {\n const taker: Resolver<T> = { resolve, reject };\n const timeoutMs = timeout ?? this.defaultTimeout;\n if (timeoutMs !== undefined) {\n taker.timeoutId = setTimeout(() => {\n const index = this.takers.indexOf(taker);\n if (index !== -1) {\n this.takers.splice(index, 1);\n }\n reject(new Error(`Take timeout after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n this.takers.push(taker);\n });\n }\n\n /**\n * This method waits for the next element, as `take` does, but it gives the element to\n * `onElement` and the closure of the queue to `onClosed`. These calls are synchronous: they\n * occur in the call that adds the element or closes the queue. The method has no timeout.\n *\n * The function that it gives withdraws the wait. A withdrawn wait gets no element, so no\n * element goes to a taker that left. `select` races its cases with this method.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no element yet.\n */\n waitTake(onElement: (element: T) => void, onClosed: (error: Error) => void): () => boolean {\n const next = this.takeNow();\n if (next.found) {\n onElement(next.element);\n return () => false;\n }\n if (this._isClosed) {\n onClosed(new Error(CLOSED_AND_EMPTY));\n return () => false;\n }\n const taker: Resolver<T> = { resolve: onElement, reject: onClosed };\n this.takers.push(taker);\n return () => {\n const index = this.takers.indexOf(taker);\n if (index === -1) return false;\n this.takers.splice(index, 1);\n return true;\n };\n }\n\n // ========================================================================\n // Non-blocking operations\n // ========================================================================\n\n /**\n * This method tries to add an element without waiting.\n * This method gives false if queue is full (with a capacity of 0: if no taker waits).\n */\n tryPut(element: T): boolean {\n if (this._isClosed) {\n return false;\n }\n return this.tryPutNow(element);\n }\n\n /**\n * This method tries to remove an element without waiting.\n * This method gives undefined if queue is empty.\n */\n tryTake(): T | undefined {\n const next = this.takeNow();\n return next.found ? next.element : undefined;\n }\n\n /** This method gives the element to a waiting taker, or puts it in the buffer when there is space. */\n private tryPutNow(element: T): boolean {\n // A waiting taker gets the element directly (the buffer is empty when a taker waits)\n const taker = this.takers.shift();\n if (taker) {\n this.wakePeekers(element);\n this.clearTimeout(taker);\n taker.resolve(element);\n return true;\n }\n if (this.buffer.length < this.capacity) {\n this.buffer.push(element);\n this.wakePeekers(element);\n return true;\n }\n return false;\n }\n\n /** Each waiting peek gets the element, which stays where it is. */\n private wakePeekers(element: T): void {\n const peekers = this.peekers;\n this.peekers = [];\n for (const peeker of peekers) {\n this.clearTimeout(peeker);\n peeker.resolve(element);\n }\n }\n\n /**\n * This method takes the next element: from the buffer (then a waiting putter moves its element into the\n * buffer), or directly from a waiting putter (a capacity of 0). (Before, the direct path\n * released the putter but did not give its element to the taker, so the taker waited forever:\n * BUGS-2026-07 C11.)\n */\n private takeNow(): { found: true; element: T } | { found: false } {\n if (this.buffer.length > 0) {\n const element = this.buffer.shift()!;\n this.admitPutter();\n return { found: true, element };\n }\n const putter = this.putters.shift();\n if (putter) {\n this.clearTimeout(putter);\n putter.resolve();\n return { found: true, element: putter.element };\n }\n return { found: false };\n }\n\n // ========================================================================\n // Peeking\n // ========================================================================\n\n /**\n * This method gives the next element without removing it.\n * Waits if queue is empty.\n */\n async peek(): Promise<T> {\n if (this.buffer.length > 0) {\n return this.buffer[0]!;\n }\n if (this.putters.length > 0) {\n return this.putters[0]!.element;\n }\n\n if (this._isClosed) {\n throw new Error(CLOSED_AND_EMPTY);\n }\n\n // Wait for the next element without a take. (Before, peek took the element and put it back\n // at the front: a take that waited after it kept waiting, and the order changed: audit pass 2.)\n return new Promise<T>((resolve, reject) => {\n const peeker: Resolver<T> = { resolve, reject };\n const timeoutMs = this.defaultTimeout;\n if (timeoutMs !== undefined) {\n peeker.timeoutId = setTimeout(() => {\n const index = this.peekers.indexOf(peeker);\n if (index !== -1) {\n this.peekers.splice(index, 1);\n }\n reject(new Error(`Peek timeout after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n this.peekers.push(peeker);\n });\n }\n\n /**\n * This method gives the next element without waiting.\n * This method gives undefined if queue is empty.\n */\n tryPeek(): T | undefined {\n return this.buffer.length > 0 ? this.buffer[0] : this.putters[0]?.element;\n }\n\n // ========================================================================\n // Closing and draining\n // ========================================================================\n\n /**\n * This method closes the queue. No more elements can be added.\n * Existing elements can still be consumed.\n */\n close(): void {\n this._isClosed = true;\n\n // Reject all waiting putters\n for (const putter of this.putters) {\n this.clearTimeout(putter);\n putter.reject(new Error(CLOSED));\n }\n this.putters = [];\n\n // Wake up takers if queue is empty\n if (this.buffer.length === 0) {\n for (const taker of this.takers) {\n this.clearTimeout(taker);\n taker.reject(new Error(CLOSED_AND_EMPTY));\n }\n this.takers = [];\n for (const peeker of this.peekers) {\n this.clearTimeout(peeker);\n peeker.reject(new Error(CLOSED_AND_EMPTY));\n }\n this.peekers = [];\n }\n }\n\n /**\n * This method drains all elements into an array.\n * This method gives immediately with current elements.\n */\n drain(): T[] {\n // The buffer, then the elements of the waiting putters, in order. (Before, the waiting\n // putters were released but their elements were dropped.)\n const elements = this.buffer.slice();\n this.buffer = [];\n for (const putter of this.putters.splice(0)) {\n this.clearTimeout(putter);\n putter.resolve();\n elements.push(putter.element);\n }\n return elements;\n }\n\n // ========================================================================\n // Async iteration\n // ========================================================================\n\n /**\n * Async iterator that yields elements as they become available.\n * Stops when queue is closed and empty.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n const next = this.takeNow();\n if (next.found) {\n yield next.element;\n } else if (this._isClosed) {\n break;\n } else {\n let element: T;\n try {\n element = await this.take();\n } catch (error) {\n // The queue was closed while the iterator waited\n if (this._isClosed) break;\n throw error;\n }\n yield element;\n }\n }\n }\n\n // ========================================================================\n // Private helpers\n // ========================================================================\n\n /** When the buffer has space, the first waiting putter moves its element into it. */\n private admitPutter(): void {\n if (this.putters.length > 0 && this.buffer.length < this.capacity) {\n const putter = this.putters.shift()!;\n this.clearTimeout(putter);\n this.buffer.push(putter.element);\n putter.resolve();\n }\n }\n\n private clearTimeout(resolver: Resolver<any>): void {\n if (resolver.timeoutId) {\n clearTimeout(resolver.timeoutId);\n }\n }\n\n // ========================================================================\n // Utility methods\n // ========================================================================\n\n /**\n * This method gives statistics about the queue.\n */\n getStats() : {\n size: number;\n capacity: number;\n isEmpty: boolean;\n isFull: boolean;\n isClosed: boolean;\n waitingPutters: number;\n waitingTakers: number;\n remainingCapacity: number;\n } {\n return {\n size: this.size,\n capacity: this.capacity,\n isEmpty: this.isEmpty,\n isFull: this.isFull,\n isClosed: this._isClosed,\n waitingPutters: this.putters.length,\n waitingTakers: this.takers.length,\n remainingCapacity: this.remainingCapacity,\n };\n }\n\n toString(): string {\n return `AsyncQueue[size=${this.size}, capacity=${this.capacity}, closed=${this._isClosed}]`;\n }\n}\n\n/**\n * Factory function to make an AsyncQueue.\n *\n * @throws RangeError if the capacity is not a whole number of 0 or more, or `Infinity`\n *\n * @example\n * const queue = asyncQueue<number>({ capacity: 100 })\n * await queue.put(42)\n * const value = await queue.take()\n */\nexport function asyncQueue<T>(options?: AsyncQueueOptions): AsyncQueue<T> {\n return new AsyncQueue<T>(options);\n}\n","/**\n * Go-style channels for CSP (Communicating Sequential Processes).\n *\n * This module gives typed, bidirectional communication channels inspired by Go.\n * Perfect for coordinating async operations and implementing concurrent patterns.\n *\n * @example\n * const ch = channel<number>()\n *\n * // Sender\n * await ch.send(42)\n *\n * // Receiver\n * const value = await ch.receive()\n *\n * // Select from multiple channels\n * const result = await select(\n * ch1.case((v) => console.log('ch1:', v)),\n * ch2.case((v) => console.log('ch2:', v))\n * )\n */\n\nimport { asyncQueue, type AsyncQueue } from \"./async-queue.js\";\n\n/**\n * Channel<T> - Bidirectional communication channel.\n *\n * The channels of Go are the model. This class gives send/receive operations\n * that can block until the other side is ready.\n *\n * @deprecated Import `Channel` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport class Channel<T> {\n private queue: AsyncQueue<T>;\n private _isClosed = false;\n\n constructor(bufferSize: number = 0) {\n // A buffer size of 0 is an unbuffered channel: send waits for a receiver (a rendezvous).\n // (Before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17.)\n this.queue = asyncQueue<T>({ capacity: bufferSize });\n }\n\n /**\n * This method sends a value through the channel.\n * The call blocks while the buffer of the channel is full.\n *\n * @throws Error if channel is closed\n */\n async send(value: T): Promise<void> {\n if (this._isClosed) {\n throw new Error(\"Cannot send on closed channel\");\n }\n await this.queue.put(value);\n }\n\n /**\n * This method receives a value from the channel.\n * The call blocks while no value is available.\n *\n * @throws Error if channel is closed and empty\n */\n async receive(): Promise<T> {\n return await this.queue.take();\n }\n\n /**\n * This method waits for one value, as `receive` does, and gives it to `onValue`. When the\n * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in\n * the call that sends the value or closes the channel.\n *\n * The function that it gives withdraws the wait, so no later value goes to it.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no value yet.\n */\n waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {\n return this.queue.waitTake(onValue, onClosed);\n }\n\n /**\n * This method tries to send without blocking.\n * This method gives false if channel is full.\n */\n trySend(value: T): boolean {\n if (this._isClosed) return false;\n return this.queue.tryPut(value);\n }\n\n /**\n * This method tries to receive without blocking.\n * This method gives undefined if no value is available.\n */\n tryReceive(): T | undefined {\n return this.queue.tryTake();\n }\n\n /**\n * This method closes the channel. No more values can be sent.\n * Receivers can still drain remaining values.\n */\n close(): void {\n this._isClosed = true;\n this.queue.close();\n }\n\n get isClosed(): boolean {\n return this._isClosed;\n }\n\n get size(): number {\n return this.queue.size;\n }\n\n /**\n * This method makes a select case for this channel.\n * The select() function uses this value for multiplexing.\n */\n case<R>(handler: (value: T) => R): SelectCase<R> {\n return {\n channel: this,\n handler,\n tryReceive: () => this.tryReceive(),\n receive: () => this.receive(),\n wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),\n };\n }\n\n /**\n * Async iteration over channel values.\n * Stops when channel is closed and empty.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n try {\n yield await this.receive();\n } catch (e) {\n // Channel closed\n break;\n }\n }\n }\n}\n\n/**\n * SelectCase represents a case in a select statement.\n *\n * @deprecated Import `SelectCase` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport interface SelectCase<R> {\n channel: Channel<any>;\n handler: (value: any) => R;\n tryReceive: () => any;\n receive: () => Promise<any>;\n /**\n * A wait for one value that `select` can withdraw: `Channel.waitReceive`. A case without it\n * uses the `waitReceive` method of its channel.\n */\n wait?: (onValue: (value: any) => void, onClosed: (error: Error) => void) => () => boolean;\n}\n\n/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */\ntype Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;\n\n/**\n * This function gives the first value of the waits, with the index of its wait. It rejects with\n * the error of the first wait whose channel is closed and empty. It withdraws each other wait in\n * the same call, so a later value stays in its channel. (Before, the receives of the cases that\n * lost stayed in their channels and dropped the next value of each: audit O56.)\n */\nfunction firstOf(waits: readonly Wait[]): Promise<{ index: number; value: unknown }> {\n return new Promise((resolve, reject) => {\n const withdraws: Array<() => boolean> = [];\n let settled = false;\n const end = (): void => {\n settled = true;\n for (const withdraw of withdraws) withdraw();\n };\n // A wait can call back at once, in its own call, when its channel has a value or is closed\n try {\n for (let index = 0; index < waits.length && !settled; index++) {\n withdraws.push(\n waits[index]!(\n (value) => {\n if (settled) return;\n end();\n resolve({ index, value });\n },\n (error) => {\n if (settled) return;\n end();\n reject(error);\n },\n ),\n );\n }\n } catch (error) {\n // A wait that throws: the waits before it are withdrawn\n if (!settled) end();\n reject(error);\n }\n });\n}\n\n/**\n * Selects from multiple channels (like Go's select statement).\n *\n * This function waits for the first channel to have a value available,\n * then calls its handler and gives the result.\n *\n * The first case with a value at once wins. The cases that lose keep no receive: a value that\n * comes later stays in its channel for the next receiver. When the channel of a case is closed\n * and empty, the given promise rejects.\n *\n * @example\n * const result = await select(\n * ch1.case((v) => `ch1: ${v}`),\n * ch2.case((v) => `ch2: ${v}`),\n * timeout(1000).case(() => 'timeout')\n * )\n *\n * @deprecated Import `select` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport async function select<R>(...cases: SelectCase<R>[]): Promise<R> {\n const { index, value } = await firstOf(\n cases.map((c): Wait => c.wait ?? ((onValue, onClosed) => c.channel.waitReceive(onValue, onClosed))),\n );\n // The handler runs after the race, not in the call of the sender\n return cases[index]!.handler(value);\n}\n\n/**\n * This function makes a timeout channel that sends after the specified duration.\n *\n * @example\n * const result = await select(\n * dataChannel.case((v) => v),\n * timeout(5000).case(() => 'timeout!')\n * )\n *\n * @deprecated Import `timeout` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function timeout(ms: number): Channel<void> {\n const ch = new Channel<void>();\n setTimeout(() => {\n ch.send(undefined).catch(() => {}); // Ignore if closed\n ch.close();\n }, ms);\n return ch;\n}\n\n/**\n * This function makes a ticker channel that sends at regular intervals.\n *\n * @example\n * const tick = ticker(1000) // Every second\n * for await (const t of tick) {\n * console.log('Tick:', t)\n * }\n *\n * @deprecated Import `ticker` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function ticker(ms: number): Channel<number> & { stop: () => void } {\n const ch = new Channel<number>(1);\n let count = 0;\n\n const intervalId = setInterval(() => {\n ch.trySend(count++);\n }, ms);\n\n return Object.assign(ch, {\n stop: () => {\n clearInterval(intervalId);\n ch.close();\n },\n });\n}\n\n/**\n * Pipeline: pipes values from input channel through transform to output channel.\n *\n * @example\n * const input = channel<number>()\n * const output = pipeline(input, (x) => x * 2)\n *\n * await input.send(5)\n * const result = await output.receive() // 10\n *\n * @deprecated Import `pipeline` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function pipeline<T, U>(\n input: Channel<T>,\n transform: (value: T) => U | Promise<U>,\n bufferSize: number = 0\n): Channel<U> {\n const output = new Channel<U>(bufferSize);\n\n // The output closes also when the transform fails, so its reader does not wait forever. The\n // error goes to the console, as in workerPool. (Before, it was an unhandled rejection: audit pass 2.)\n (async () => {\n try {\n for await (const value of input) {\n const transformed = await transform(value);\n await output.send(transformed);\n }\n } finally {\n output.close();\n }\n })().catch((error: unknown) => console.error(\"pipeline error:\", error));\n\n return output;\n}\n\n/**\n * Fan-out: distributes values from one input channel to multiple output channels.\n *\n * @example\n * const input = channel<number>()\n * const [out1, out2, out3] = fanOut(input, 3)\n *\n * // Each output gets a copy of every input value\n *\n * @deprecated Import `fanOut` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function fanOut<T>(input: Channel<T>, count: number, bufferSize: number = 0): Channel<T>[] {\n const outputs = Array.from({ length: count }, () => new Channel<T>(bufferSize));\n\n (async () => {\n try {\n for await (const value of input) {\n await Promise.all(outputs.map((ch) => ch.send(value)));\n }\n } finally {\n outputs.forEach((ch) => ch.close());\n }\n })().catch((error: unknown) => console.error(\"fanOut error:\", error));\n\n return outputs;\n}\n\n/**\n * Fan-in: this function merges multiple input channels into one output channel.\n *\n * @example\n * const ch1 = channel<number>()\n * const ch2 = channel<number>()\n * const merged = fanIn(ch1, ch2)\n *\n * // merged receives values from both ch1 and ch2\n *\n * @deprecated Import `fanIn` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function fanIn<T>(...inputs: Channel<T>[]): Channel<T> {\n const output = new Channel<T>();\n\n const workers = inputs.map(async (input) => {\n for await (const value of input) {\n await output.send(value);\n }\n });\n\n // All the workers settle, then the output closes, also after a failed send\n Promise.allSettled(workers).then((results) => {\n output.close();\n for (const result of results) if (result.status === \"rejected\") console.error(\"fanIn error:\", result.reason);\n });\n\n return output;\n}\n\n/**\n * Merge: like fanIn but closes output when first input closes.\n *\n * It takes one value at a time, from the inputs in turn. It keeps no receive on an input while\n * it waits for the reader of the output. Thus each value of each input reaches the output one\n * time, in the order of its input, or stays in its input.\n *\n * @deprecated Import `merge` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function merge<T>(...inputs: Channel<T>[]): Channel<T> {\n const output = new Channel<T>();\n\n (async () => {\n // The input after the input of the last value comes first, so a busy input starves no other\n let start = 0;\n while (true) {\n const order = inputs.map((_, offset) => (start + offset) % inputs.length);\n let next: { index: number; value: unknown };\n try {\n next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));\n } catch {\n // An input is closed and empty\n break;\n }\n const index = order[next.index]!;\n start = (index + 1) % inputs.length;\n try {\n await output.send(next.value as T);\n } catch {\n // The reader closed the output\n break;\n }\n }\n output.close();\n })();\n\n return output;\n}\n\n/**\n * Buffered channel with specified capacity.\n *\n * @deprecated Import `buffered` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function buffered<T>(capacity: number): Channel<T> {\n return new Channel<T>(capacity);\n}\n\n/**\n * Unbuffered channel (rendezvous point).\n * Sends block until receiver is ready.\n *\n * @deprecated Import `unbuffered` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function unbuffered<T>(): Channel<T> {\n return new Channel<T>(0);\n}\n\n/**\n * Factory function to make a channel.\n *\n * @example\n * const ch = channel<number>()\n * const bufferedCh = channel<string>(10)\n *\n * @deprecated Import `channel` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function channel<T>(bufferSize: number = 0): Channel<T> {\n return new Channel<T>(bufferSize);\n}\n\n/**\n * WorkerPool: distributes work across multiple workers.\n *\n * @example\n * const pool = workerPool(\n * jobChannel,\n * async (job) => await processJob(job),\n * { workers: 4 }\n * )\n *\n * // 4 workers concurrently process jobs from jobChannel\n *\n * @deprecated Import `workerPool` from `@mark1russell7/service/channel`. The next MINOR version of collections removes it.\n */\nexport function workerPool<T, R>(\n jobs: Channel<T>,\n worker: (job: T) => Promise<R>,\n options: { workers: number; bufferSize?: number } = { workers: 1 }\n): Channel<R> {\n const results = new Channel<R>(options.bufferSize || 0);\n const { workers: workerCount } = options;\n\n const workers = Array.from({ length: workerCount }, async () => {\n for await (const job of jobs) {\n try {\n const result = await worker(job);\n await results.send(result);\n } catch (error) {\n console.error(\"Worker error:\", error);\n }\n }\n });\n\n Promise.all(workers).then(() => results.close());\n\n return results;\n}\n","/**\n * asSettled - The results of running promises, in the order that they settle.\n *\n * @example\n * const pages = urls.map((url) => fetch(url));\n * for await (const result of asSettled(pages)) {\n * if (result.status === \"fulfilled\") show(result.index, result.value);\n * else report(result.index, result.reason);\n * }\n */\n\n/** One result of `asSettled`: the index of its promise in the input, and how the promise settled. */\nexport type Settled<T> = { readonly index: number } & PromiseSettledResult<T>;\n\n/**\n * This function gives the result of each promise when it settles, in settle order, not in input\n * order. The promises run already: this function starts nothing. Each result has the index of its\n * promise in the input. A rejected promise gives `status: \"rejected\"` and its reason: the\n * generator does not throw it. When the consumer stops early, the other promises continue, and\n * their rejections are not reported as unhandled.\n */\nexport async function* asSettled<T>(promises: Iterable<Promise<T>>): AsyncGenerator<Settled<T>, void, undefined> {\n const pending = new Map<number, Promise<Settled<T>>>();\n let next = 0;\n for (const promise of promises) {\n const index = next;\n next += 1;\n pending.set(\n index,\n Promise.resolve(promise).then(\n (value): Settled<T> => ({ index, status: \"fulfilled\", value }),\n (reason: unknown): Settled<T> => ({ index, status: \"rejected\", reason })\n )\n );\n }\n while (pending.size > 0) {\n const settled = await Promise.race(pending.values());\n pending.delete(settled.index);\n yield settled;\n }\n}\n","/**\n * semaphore - A bound on the tasks that run at the same time.\n *\n * @example\n * const writes = semaphore(4);\n * // At most 4 writes run at once. The others wait in the order that they came.\n * await Promise.all(items.map((item) => writes.run(() => store.set(item.id, item))));\n */\n\n/** A semaphore: a count of permits, and a queue of the callers that wait for one. */\nexport interface Semaphore {\n /** The permits of the semaphore. */\n readonly permits: number;\n /** The permits that no caller holds. */\n readonly available: number;\n /** The callers that wait for a permit. */\n readonly waiting: number;\n /**\n * This method gives a permit. It waits while all permits are held. The waiting callers get the permits in the order\n * that they came. The result is the release of the permit. A second call of the release does nothing.\n */\n acquire(): Promise<() => void>;\n /** This method starts a task with a permit. The permit goes back when the task ends, also when it throws. */\n run<R>(task: () => R | PromiseLike<R>): Promise<R>;\n}\n\n/**\n * This function makes a semaphore with `permits` permits. The value is a whole number of 1 or more, or `Infinity`\n * for no bound. Another value throws a `RangeError`.\n */\nexport function semaphore(permits: number): Semaphore {\n if (!(permits === Infinity || (Number.isInteger(permits) && permits >= 1))) {\n throw new RangeError(`A semaphore needs a whole number of permits of 1 or more, or Infinity: ${permits}`);\n }\n let held = 0;\n // The waiting callers, in the order that they came. A release gives its permit to the first.\n const queue: Array<() => void> = [];\n let head = 0;\n\n const releaseOnce = (): (() => void) => {\n let done = false;\n return () => {\n if (done) return;\n done = true;\n if (head < queue.length) {\n const next = queue[head]!;\n head += 1;\n // The permit goes from the releaser to the next caller, so `held` does not change\n if (head > 64 && head * 2 > queue.length) {\n queue.splice(0, head);\n head = 0;\n }\n next();\n } else {\n held -= 1;\n }\n };\n };\n\n const acquire = (): Promise<() => void> => {\n if (held < permits) {\n held += 1;\n return Promise.resolve(releaseOnce());\n }\n return new Promise((resolve) => {\n queue.push(() => resolve(releaseOnce()));\n });\n };\n\n return {\n permits,\n get available() {\n return permits - held;\n },\n get waiting() {\n return queue.length - head;\n },\n acquire,\n async run<R>(task: () => R | PromiseLike<R>): Promise<R> {\n const release = await acquire();\n try {\n return await task();\n } finally {\n release();\n }\n },\n };\n}\n","/**\n * Functional operations for iterables (lazy sync transforms).\n *\n * This module gives Stream-like operations with lazy evaluation.\n * All operations return generators for composability.\n *\n * @example\n * const result = pipe(\n * [1, 2, 3, 4, 5],\n * (it) => map(it, x => x * 2),\n * (it) => filter(it, x => x > 5),\n * (it) => take(it, 2),\n * toArray\n * ) // [6, 8]\n */\n\n// ============================================================================\n// Mapping and transformation\n// ============================================================================\n\n/**\n * This function maps each element through a function.\n *\n * @example\n * const doubled = map([1, 2, 3], x => x * 2) // [2, 4, 6]\n */\nexport function* map<T, U>(\n iterable: Iterable<T>,\n fn: (value: T, index: number) => U\n): Generator<U> {\n let index = 0;\n for (const value of iterable) {\n yield fn(value, index++);\n }\n}\n\n/**\n * This function filters elements based on a predicate.\n */\nexport function* filter<T>(\n iterable: Iterable<T>,\n predicate: (value: T, index: number) => boolean\n): Generator<T> {\n let index = 0;\n for (const value of iterable) {\n if (predicate(value, index++)) {\n yield value;\n }\n }\n}\n\n/**\n * This function flatMaps each element to an iterable and flattens.\n */\nexport function* flatMap<T, U>(\n iterable: Iterable<T>,\n fn: (value: T, index: number) => Iterable<U>\n): Generator<U> {\n let index = 0;\n for (const value of iterable) {\n yield* fn(value, index++);\n }\n}\n\n/**\n * This function flattens a nested iterable.\n */\nexport function* flatten<T>(iterable: Iterable<Iterable<T>>): Generator<T> {\n for (const inner of iterable) {\n yield* inner;\n }\n}\n\n// ============================================================================\n// Limiting and skipping\n// ============================================================================\n\n/**\n * This function takes the first n elements. It reads no element after the n-th one, and it reads nothing when n is 0.\n */\nexport function* take<T>(iterable: Iterable<T>, n: number): Generator<T> {\n if (n <= 0) return;\n let count = 0;\n for (const value of iterable) {\n yield value;\n if (++count >= n) return;\n }\n}\n\n/**\n * This function skips the first n elements.\n */\nexport function* skip<T>(iterable: Iterable<T>, n: number): Generator<T> {\n let count = 0;\n for (const value of iterable) {\n if (count++ >= n) {\n yield value;\n }\n }\n}\n\n/**\n * This function takes elements while predicate is true.\n */\nexport function* takeWhile<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): Generator<T> {\n for (const value of iterable) {\n if (!predicate(value)) break;\n yield value;\n }\n}\n\n/**\n * This function skips elements while predicate is true.\n */\nexport function* skipWhile<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): Generator<T> {\n let skipping = true;\n for (const value of iterable) {\n if (skipping && predicate(value)) continue;\n skipping = false;\n yield value;\n }\n}\n\n// ============================================================================\n// Combining\n// ============================================================================\n\n/**\n * Concatenates multiple iterables.\n */\nexport function* concat<T>(...iterables: Iterable<T>[]): Generator<T> {\n for (const iterable of iterables) {\n yield* iterable;\n }\n}\n\n/**\n * Zips multiple iterables together.\n */\nexport function* zip<T extends any[]>(\n ...iterables: { [K in keyof T]: Iterable<T[K]> }\n): Generator<T> {\n const iterators = iterables.map((it) => it[Symbol.iterator]());\n\n while (true) {\n const results = iterators.map((it) => it.next());\n if (results.some((r) => r.done)) break;\n yield results.map((r) => r.value) as T;\n }\n}\n\n/**\n * Zips with index.\n */\nexport function* enumerate<T>(iterable: Iterable<T>): Generator<[number, T]> {\n let index = 0;\n for (const value of iterable) {\n yield [index++, value];\n }\n}\n\n// ============================================================================\n// Partitioning\n// ============================================================================\n\n/**\n * Chunks elements into arrays of specified size.\n */\nexport function* chunk<T>(iterable: Iterable<T>, size: number): Generator<T[]> {\n let chunk: T[] = [];\n for (const value of iterable) {\n chunk.push(value);\n if (chunk.length === size) {\n yield chunk;\n chunk = [];\n }\n }\n if (chunk.length > 0) {\n yield chunk;\n }\n}\n\n/**\n * This function makes a sliding window of specified size.\n */\nexport function* window<T>(iterable: Iterable<T>, size: number): Generator<T[]> {\n const window: T[] = [];\n for (const value of iterable) {\n window.push(value);\n if (window.length > size) {\n window.shift();\n }\n if (window.length === size) {\n yield [...window];\n }\n }\n}\n\n/**\n * Partitions elements into two arrays based on predicate.\n */\nexport function partition<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): [T[], T[]] {\n const truthy: T[] = [];\n const falsy: T[] = [];\n\n for (const value of iterable) {\n if (predicate(value)) {\n truthy.push(value);\n } else {\n falsy.push(value);\n }\n }\n\n return [truthy, falsy];\n}\n\n// ============================================================================\n// Reducing and folding\n// ============================================================================\n\n/**\n * This function reduces iterable to a single value.\n */\nexport function reduce<T, U>(\n iterable: Iterable<T>,\n fn: (acc: U, value: T, index: number) => U,\n initial: U\n): U {\n let acc = initial;\n let index = 0;\n for (const value of iterable) {\n acc = fn(acc, value, index++);\n }\n return acc;\n}\n\n/**\n * Scans (like reduce but emits intermediate results).\n */\nexport function* scan<T, U>(\n iterable: Iterable<T>,\n fn: (acc: U, value: T) => U,\n initial: U\n): Generator<U> {\n let acc = initial;\n yield acc;\n for (const value of iterable) {\n acc = fn(acc, value);\n yield acc;\n }\n}\n\n// ============================================================================\n// Sorting and ordering\n// ============================================================================\n\n/**\n * This function sorts elements (materializes the iterable).\n */\nexport function* sort<T>(\n iterable: Iterable<T>,\n compare?: (a: T, b: T) => number\n): Generator<T> {\n const array = Array.from(iterable);\n array.sort(compare);\n yield* array;\n}\n\n/**\n * Reverses elements (materializes the iterable).\n */\nexport function* reverse<T>(iterable: Iterable<T>): Generator<T> {\n const array = Array.from(iterable);\n array.reverse();\n yield* array;\n}\n\n// ============================================================================\n// Distinct and uniqueness\n// ============================================================================\n\n/**\n * This function removes duplicate elements (by reference or key function).\n */\nexport function* distinct<T, K = T>(\n iterable: Iterable<T>,\n keyFn?: (value: T) => K\n): Generator<T> {\n const seen = new Set<K>();\n for (const value of iterable) {\n const key = (keyFn ? keyFn(value) : value) as K;\n if (!seen.has(key)) {\n seen.add(key);\n yield value;\n }\n }\n}\n\n/**\n * This function removes consecutive duplicates.\n */\nexport function* distinctConsecutive<T, K = T>(\n iterable: Iterable<T>,\n keyFn?: (value: T) => K\n): Generator<T> {\n let lastKey: K | undefined;\n let first = true;\n\n for (const value of iterable) {\n const key = (keyFn ? keyFn(value) : value) as K;\n if (first || key !== lastKey) {\n yield value;\n lastKey = key;\n first = false;\n }\n }\n}\n\n// ============================================================================\n// Peeking and side effects\n// ============================================================================\n\n/**\n * This function does a side effect for each element. The stream does not change.\n */\nexport function* tap<T>(\n iterable: Iterable<T>,\n fn: (value: T, index: number) => void\n): Generator<T> {\n let index = 0;\n for (const value of iterable) {\n fn(value, index++);\n yield value;\n }\n}\n\n// ============================================================================\n// Predicates and checks\n// ============================================================================\n\n/**\n * This function gives true if any element matches the predicate.\n */\nexport function some<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): boolean {\n for (const value of iterable) {\n if (predicate(value)) return true;\n }\n return false;\n}\n\n/**\n * This function gives true if all elements match the predicate.\n */\nexport function every<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): boolean {\n for (const value of iterable) {\n if (!predicate(value)) return false;\n }\n return true;\n}\n\n/**\n * This function gives true if no elements match the predicate.\n */\nexport function none<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): boolean {\n return !some(iterable, predicate);\n}\n\n/**\n * This function finds the first element matching the predicate.\n */\nexport function find<T>(\n iterable: Iterable<T>,\n predicate: (value: T) => boolean\n): T | undefined {\n for (const value of iterable) {\n if (predicate(value)) return value;\n }\n return undefined;\n}\n\n/**\n * This function counts elements (optionally matching a predicate).\n */\nexport function count<T>(\n iterable: Iterable<T>,\n predicate?: (value: T) => boolean\n): number {\n let count = 0;\n for (const value of iterable) {\n if (!predicate || predicate(value)) {\n count++;\n }\n }\n return count;\n}\n\n// ============================================================================\n// Min/Max\n// ============================================================================\n\n/**\n * This function gives the minimum element.\n */\nexport function min<T>(\n iterable: Iterable<T>,\n compare?: (a: T, b: T) => number\n): T | undefined {\n const cmp = compare || ((a: any, b: any) => a - b);\n let minValue: T | undefined;\n\n for (const value of iterable) {\n if (minValue === undefined || cmp(value, minValue) < 0) {\n minValue = value;\n }\n }\n\n return minValue;\n}\n\n/**\n * This function gives the maximum element.\n */\nexport function max<T>(\n iterable: Iterable<T>,\n compare?: (a: T, b: T) => number\n): T | undefined {\n const cmp = compare || ((a: any, b: any) => a - b);\n let maxValue: T | undefined;\n\n for (const value of iterable) {\n if (maxValue === undefined || cmp(value, maxValue) > 0) {\n maxValue = value;\n }\n }\n\n return maxValue;\n}\n\n/**\n * This function gives the sum of elements.\n */\nexport function sum(iterable: Iterable<number>): number {\n let total = 0;\n for (const value of iterable) {\n total += value;\n }\n return total;\n}\n\n/**\n * This function gives the average of elements.\n */\nexport function average(iterable: Iterable<number>): number | undefined {\n let total = 0;\n let count = 0;\n\n for (const value of iterable) {\n total += value;\n count++;\n }\n\n return count === 0 ? undefined : total / count;\n}\n\n// ============================================================================\n// Terminal operations (materialization)\n// ============================================================================\n\n/**\n * This function collects elements into an array.\n */\nexport function toArray<T>(iterable: Iterable<T>): T[] {\n return Array.from(iterable);\n}\n\n/**\n * This function collects elements into a Set.\n */\nexport function toSet<T>(iterable: Iterable<T>): Set<T> {\n return new Set(iterable);\n}\n\n/**\n * This function collects elements into a Map.\n */\nexport function toMap<T, K, V>(\n iterable: Iterable<T>,\n keyFn: (value: T) => K,\n valueFn: (value: T) => V\n): Map<K, V> {\n const map = new Map<K, V>();\n for (const value of iterable) {\n map.set(keyFn(value), valueFn(value));\n }\n return map;\n}\n\n// ============================================================================\n// Pipe utility for composition\n// ============================================================================\n\n/**\n * This function pipes a value through a series of transformations.\n *\n * @example\n * const result = pipe(\n * [1, 2, 3, 4, 5],\n * (it) => map(it, x => x * 2),\n * (it) => filter(it, x => x > 5),\n * (it) => take(it, 2),\n * toArray\n * ) // [6, 8]\n */\nexport function pipe<T>(\n value: T,\n ...fns: Array<(value: any) => any>\n): any {\n return fns.reduce((acc, fn) => fn(acc), value);\n}\n","/**\n * Collectors for Stream-style collection operations.\n *\n * This module gives Java Stream API-style collectors for transforming iterables\n * into various collection types. The model is java.util.stream.Collectors.\n *\n * @example\n * import { collect, toList, groupingBy } from './collectors'\n *\n * const grouped = collect(users, groupingBy(u => u.age))\n */\n\nimport { arrayList, type ArrayList } from \"../impl/array-list.js\";\nimport { hashMap, type HashMap } from \"../impl/hash-map.js\";\nimport { hashSet, type HashSet } from \"../impl/hash-set.js\";\n\n// ============================================================================\n// Collector interface\n// ============================================================================\n\n/**\n * A Collector represents a mutable reduction operation.\n *\n * @template T - The type of input elements\n * @template A - The mutable accumulation type\n * @template R - The final result type\n */\nexport interface Collector<T, A, R> {\n /**\n * This value makes the initial accumulator.\n */\n supplier: () => A;\n\n /**\n * This value incorporates an element into the accumulator and gives the next accumulator. A mutable\n * accumulator (a list, a map) gives itself. An immutable one (a count, a sum) gives the\n * new value. (Before, the result was ignored, so every immutable collector - counting,\n * summing, minBy, maxBy, reducing, first, last - given its seed: BUGS-2026-07 C12.)\n */\n accumulator: (acc: A, element: T) => A;\n\n /**\n * This value combines two accumulators (for parallel streams).\n */\n combiner?: (acc1: A, acc2: A) => A;\n\n /**\n * This value transforms the accumulator into the final result.\n */\n finisher: (acc: A) => R;\n}\n\n/**\n * This function collects elements using a collector.\n *\n * @example\n * const list = collect([1, 2, 3], toList())\n * const set = collect([1, 2, 2, 3], toSet())\n */\nexport function collect<T, A, R>(\n iterable: Iterable<T>,\n collector: Collector<T, A, R>\n): R {\n let acc = collector.supplier();\n for (const element of iterable) {\n acc = collector.accumulator(acc, element);\n }\n return collector.finisher(acc);\n}\n\n// ============================================================================\n// Basic collectors\n// ============================================================================\n\n/**\n * This function collects elements into an ArrayList.\n */\nexport function toList<T>(): Collector<T, ArrayList<T>, ArrayList<T>> {\n return {\n supplier: () => arrayList<T>(),\n accumulator: (list, element) => (list.add(element), list),\n finisher: (list) => list,\n };\n}\n\n/**\n * This function collects elements into a HashSet.\n */\nexport function toSet<T>(): Collector<T, HashSet<T>, HashSet<T>> {\n return {\n supplier: () => hashSet<T>(),\n accumulator: (set, element) => (set.add(element), set),\n finisher: (set) => set,\n };\n}\n\n/**\n * This function collects elements into a native Array.\n */\nexport function toArray<T>(): Collector<T, T[], T[]> {\n return {\n supplier: () => [],\n accumulator: (arr, element) => (arr.push(element), arr),\n finisher: (arr) => arr,\n };\n}\n\n/**\n * This function collects elements into a HashMap using key and value extractors.\n */\nexport function toMap<T, K, V>(\n keyExtractor: (element: T) => K,\n valueExtractor: (element: T) => V\n): Collector<T, HashMap<K, V>, HashMap<K, V>> {\n return {\n supplier: () => hashMap<K, V>(),\n accumulator: (map, element) => {\n map.set(keyExtractor(element), valueExtractor(element));\n return map;\n },\n finisher: (map) => map,\n };\n}\n\n// ============================================================================\n// Grouping collectors\n// ============================================================================\n\n/**\n * This function groups elements by a classifier function.\n *\n * @example\n * const byAge = collect(users, groupingBy(u => u.age))\n * // Map<number, ArrayList<User>>\n */\nexport function groupingBy<T, K>(\n classifier: (element: T) => K\n): Collector<T, HashMap<K, ArrayList<T>>, HashMap<K, ArrayList<T>>> {\n return {\n supplier: () => hashMap<K, ArrayList<T>>(),\n accumulator: (map, element) => {\n const key = classifier(element);\n const list = map.computeIfAbsent(key, () => arrayList<T>());\n list.add(element);\n return map;\n },\n finisher: (map) => map,\n };\n}\n\n/**\n * This function groups the elements and transforms each group with a downstream collector.\n *\n * @example\n * const countByAge = collect(\n * users,\n * groupingBy(u => u.age, counting())\n * )\n * // Map<number, number>\n */\nexport function groupingByWith<T, K, A, D>(\n classifier: (element: T) => K,\n downstream: Collector<T, A, D>\n): Collector<T, HashMap<K, A>, HashMap<K, D>> {\n return {\n supplier: () => hashMap<K, A>(),\n accumulator: (map, element) => {\n const key = classifier(element);\n const acc = map.has(key) ? map.get(key) : downstream.supplier();\n map.set(key, downstream.accumulator(acc, element));\n return map;\n },\n finisher: (map) => {\n const result = hashMap<K, D>();\n for (const entry of map.entries()) {\n result.set(entry.key, downstream.finisher(entry.value));\n }\n return result;\n },\n };\n}\n\n/**\n * Partitions elements into two groups based on a predicate.\n *\n * @example\n * const partitioned = collect(\n * numbers,\n * partitioningBy(n => n % 2 === 0)\n * )\n * // Map<boolean, ArrayList<number>>\n */\nexport function partitioningBy<T>(\n predicate: (element: T) => boolean\n): Collector<T, HashMap<boolean, ArrayList<T>>, HashMap<boolean, ArrayList<T>>> {\n return groupingBy((element) => predicate(element));\n}\n\n// ============================================================================\n// Aggregation collectors\n// ============================================================================\n\n/**\n * This function counts the number of elements.\n */\nexport function counting<T>(): Collector<T, number, number> {\n return {\n supplier: () => 0,\n accumulator: (count) => count + 1,\n finisher: (count) => count,\n };\n}\n\n/**\n * Sums numeric elements.\n */\nexport function summingNumber<T>(\n mapper: (element: T) => number\n): Collector<T, number, number> {\n return {\n supplier: () => 0,\n accumulator: (sum, element) => sum + mapper(element),\n finisher: (sum) => sum,\n };\n}\n\n/**\n * Averages numeric elements.\n */\nexport function averagingNumber<T>(\n mapper: (element: T) => number\n): Collector<T, { sum: number; count: number }, number> {\n return {\n supplier: () => ({ sum: 0, count: 0 }),\n accumulator: (acc, element) => {\n acc.sum += mapper(element);\n acc.count++;\n return acc;\n },\n finisher: (acc) => (acc.count === 0 ? 0 : acc.sum / acc.count),\n };\n}\n\n/**\n * This function finds the minimum element.\n */\nexport function minBy<T>(\n comparator: (a: T, b: T) => number\n): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (min, element) => {\n if (min === undefined || comparator(element, min) < 0) {\n return element;\n }\n return min;\n },\n finisher: (min) => min,\n };\n}\n\n/**\n * This function finds the maximum element.\n */\nexport function maxBy<T>(\n comparator: (a: T, b: T) => number\n): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (max, element) => {\n if (max === undefined || comparator(element, max) > 0) {\n return element;\n }\n return max;\n },\n finisher: (max) => max,\n };\n}\n\n// ============================================================================\n// String collectors\n// ============================================================================\n\n/**\n * Joins elements into a string.\n *\n * @example\n * const csv = collect(['a', 'b', 'c'], joining(', '))\n * // \"a, b, c\"\n *\n * const bracketed = collect(\n * ['a', 'b', 'c'],\n * joining(', ', '[', ']')\n * )\n * // \"[a, b, c]\"\n */\nexport function joining<T>(\n delimiter: string = \"\",\n prefix: string = \"\",\n suffix: string = \"\"\n): Collector<T, string[], string> {\n return {\n supplier: () => [],\n accumulator: (parts, element) => (parts.push(String(element)), parts),\n finisher: (parts) => prefix + parts.join(delimiter) + suffix,\n };\n}\n\n// ============================================================================\n// Mapping collectors\n// ============================================================================\n\n/**\n * This function applies a mapping function before collecting.\n *\n * @example\n * const names = collect(\n * users,\n * mapping(u => u.name, toList())\n * )\n */\nexport function mapping<T, U, A, R>(\n mapper: (element: T) => U,\n downstream: Collector<U, A, R>\n): Collector<T, A, R> {\n return {\n supplier: downstream.supplier,\n accumulator: (acc, element) => downstream.accumulator(acc, mapper(element)),\n finisher: downstream.finisher,\n };\n}\n\n/**\n * This function filters elements before collecting.\n */\nexport function filtering<T, A, R>(\n predicate: (element: T) => boolean,\n downstream: Collector<T, A, R>\n): Collector<T, A, R> {\n return {\n supplier: downstream.supplier,\n accumulator: (acc, element) => {\n return predicate(element) ? downstream.accumulator(acc, element) : acc;\n },\n finisher: downstream.finisher,\n };\n}\n\n/**\n * FlatMaps elements before collecting.\n */\nexport function flatMapping<T, U, A, R>(\n mapper: (element: T) => Iterable<U>,\n downstream: Collector<U, A, R>\n): Collector<T, A, R> {\n return {\n supplier: downstream.supplier,\n accumulator: (acc, element) => {\n for (const mapped of mapper(element)) {\n acc = downstream.accumulator(acc, mapped);\n }\n return acc;\n },\n finisher: downstream.finisher,\n };\n}\n\n// ============================================================================\n// Reducing collectors\n// ============================================================================\n\n/**\n * General reduction collector.\n */\nexport function reducing<T>(\n identity: T,\n reducer: (acc: T, element: T) => T\n): Collector<T, T, T> {\n return {\n supplier: () => identity,\n accumulator: (acc, element) => reducer(acc, element),\n finisher: (acc) => acc,\n };\n}\n\n/**\n * Reducing with mapper.\n */\nexport function reducingWith<T, U>(\n identity: U,\n mapper: (element: T) => U,\n reducer: (acc: U, mapped: U) => U\n): Collector<T, U, U> {\n return {\n supplier: () => identity,\n accumulator: (acc, element) => reducer(acc, mapper(element)),\n finisher: (acc) => acc,\n };\n}\n\n// ============================================================================\n// Composite collectors\n// ============================================================================\n\n/**\n * This function collects with two collectors and combines results.\n *\n * @example\n * const stats = collect(\n * numbers,\n * teeing(\n * summingNumber(n => n),\n * counting(),\n * (sum, count) => ({ sum, count, avg: sum / count })\n * )\n * )\n */\nexport function teeing<T, A1, A2, R1, R2, R>(\n collector1: Collector<T, A1, R1>,\n collector2: Collector<T, A2, R2>,\n combiner: (r1: R1, r2: R2) => R\n): Collector<T, [A1, A2], R> {\n return {\n supplier: () => [collector1.supplier(), collector2.supplier()] as [A1, A2],\n accumulator: ([acc1, acc2], element) => [\n collector1.accumulator(acc1, element),\n collector2.accumulator(acc2, element),\n ],\n finisher: ([acc1, acc2]) => {\n return combiner(collector1.finisher(acc1), collector2.finisher(acc2));\n },\n };\n}\n\n// ============================================================================\n// Utility collectors\n// ============================================================================\n\n/**\n * This function collects the first element.\n */\nexport function first<T>(): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (first, element) => (first === undefined ? element : first),\n finisher: (first) => first,\n };\n}\n\n/**\n * This function collects the last element.\n */\nexport function last<T>(): Collector<T, T | undefined, T | undefined> {\n return {\n supplier: () => undefined,\n accumulator: (_last, element) => element,\n finisher: (last) => last,\n };\n}\n\n/**\n * This type makes summary statistics.\n */\nexport interface SummaryStatistics {\n count: number;\n sum: number;\n min: number;\n max: number;\n average: number;\n}\n\nexport function summarizingNumber<T>(\n mapper: (element: T) => number\n): Collector<T, Partial<SummaryStatistics>, SummaryStatistics> {\n return {\n supplier: () => ({\n count: 0,\n sum: 0,\n min: Infinity,\n max: -Infinity,\n }),\n accumulator: (stats, element) => {\n const value = mapper(element);\n // The supplier sets every field. (Before, `stats.min || Infinity` treated a minimum of 0\n // as missing: BUGS-2026-07 L16.)\n stats.count = stats.count! + 1;\n stats.sum = stats.sum! + value;\n stats.min = Math.min(stats.min!, value);\n stats.max = Math.max(stats.max!, value);\n return stats;\n },\n finisher: (stats) => ({\n count: stats.count!,\n sum: stats.sum!,\n min: stats.min!,\n max: stats.max!,\n average: stats.count! === 0 ? 0 : stats.sum! / stats.count!,\n }),\n };\n}\n","/**\n * Factory utilities for making collections.\n *\n * This module gives convenient factory methods similar to Java's Collections class.\n * These functions mirror Java methods like Collections.emptyList() and singletonList().\n */\n\nimport { arrayList, ArrayList } from \"../impl/array-list.js\";\nimport { arrayDeque, ArrayDeque } from \"../impl/array-deque.js\";\nimport { hashMap, HashMap } from \"../impl/hash-map.js\";\nimport type { List } from \"../interfaces/list.js\";\nimport type { Queue } from \"../interfaces/queue.js\";\nimport type { MapLike } from \"../interfaces/map.js\";\nimport { readonly } from \"../behaviors/readonly.js\";\nimport { compose } from \"../core/middleware.js\";\n\n// ============================================================================\n// Empty collections\n// ============================================================================\n\n/**\n * This value is an empty, immutable list.\n * Multiple calls return the same instance (singleton pattern).\n *\n * @example\n * const list = emptyList<number>()\n * list.size // 0\n * list.add(1) // Error: Cannot modify readonly collection\n */\nconst EMPTY_LIST_CACHE = new Map<any, any>();\n\nexport function emptyList<T>(): List<T> {\n const key = \"list\";\n if (!EMPTY_LIST_CACHE.has(key)) {\n const list = compose(readonly<List<T>>())(arrayList<T>());\n EMPTY_LIST_CACHE.set(key, list);\n }\n return EMPTY_LIST_CACHE.get(key);\n}\n\n/**\n * This value is an empty, immutable queue.\n */\nconst EMPTY_QUEUE_CACHE = new Map<any, any>();\n\nexport function emptyQueue<T>(): Queue<T> {\n const key = \"queue\";\n if (!EMPTY_QUEUE_CACHE.has(key)) {\n const queue = compose(readonly<Queue<T>>())(arrayDeque<T>() as Queue<T>);\n EMPTY_QUEUE_CACHE.set(key, queue);\n }\n return EMPTY_QUEUE_CACHE.get(key);\n}\n\n/**\n * This value is an empty, immutable map.\n */\nconst EMPTY_MAP_CACHE = new Map<any, any>();\n\nexport function emptyMap<K, V>(): MapLike<K, V> {\n const key = \"map\";\n if (!EMPTY_MAP_CACHE.has(key)) {\n const map = compose(readonly<MapLike<K, V>>())(hashMap<K, V>());\n EMPTY_MAP_CACHE.set(key, map);\n }\n return EMPTY_MAP_CACHE.get(key);\n}\n\n// ============================================================================\n// Singleton collections (single element)\n// ============================================================================\n\n/**\n * This function gives an immutable list containing only the specified element.\n *\n * @example\n * const list = singletonList(42)\n * list.size // 1\n * list.get(0) // 42\n * list.add(2) // Error: Cannot modify readonly collection\n */\nexport function singletonList<T>(element: T): List<T> {\n const list = arrayList<T>();\n list.add(element);\n return compose(readonly<List<T>>())(list);\n}\n\n/**\n * This function gives an immutable map containing only the specified key-value mapping.\n */\nexport function singletonMap<K, V>(key: K, value: V): MapLike<K, V> {\n const map = hashMap<K, V>();\n map.set(key, value);\n return compose(readonly<MapLike<K, V>>())(map);\n}\n\n// ============================================================================\n// N-copies collections\n// ============================================================================\n\n/**\n * This function gives an immutable list consisting of n copies of the specified element.\n *\n * @example\n * const list = nCopies(5, 'hello')\n * list.size // 5\n * list.get(2) // 'hello'\n */\nexport function nCopies<T>(n: number, element: T): List<T> {\n if (n < 0) {\n throw new Error(`n must be non-negative, got ${n}`);\n }\n\n const list = arrayList<T>();\n for (let i = 0; i < n; i++) {\n list.add(element);\n }\n return compose(readonly<List<T>>())(list);\n}\n\n// ============================================================================\n// Collection creation from iterables\n// ============================================================================\n\n/**\n * This function makes a new ArrayList from the given elements.\n *\n * @example\n * const list = listOf(1, 2, 3, 4, 5)\n */\nexport function listOf<T>(...elements: T[]): ArrayList<T> {\n return arrayList(elements);\n}\n\n/**\n * This function makes a new ArrayDeque from the given elements.\n */\nexport function queueOf<T>(...elements: T[]): ArrayDeque<T> {\n return arrayDeque(elements);\n}\n\n/**\n * This function makes a new HashMap from the given key-value pairs.\n *\n * @example\n * const map = mapOf(['a', 1], ['b', 2], ['c', 3])\n */\nexport function mapOf<K, V>(...entries: [K, V][]): HashMap<K, V> {\n return hashMap(entries);\n}\n\n// ============================================================================\n// Mutable collection factories\n// ============================================================================\n\n/**\n * This function makes a new mutable ArrayList with optional initial elements.\n *\n * @example\n * const list = mutableListOf(1, 2, 3)\n * list.add(4)\n */\nexport function mutableListOf<T>(...elements: T[]): ArrayList<T> {\n return arrayList(elements);\n}\n\n/**\n * This function makes a new mutable HashMap with optional initial entries.\n */\nexport function mutableMapOf<K, V>(...entries: [K, V][]): HashMap<K, V> {\n return hashMap(entries);\n}\n\n// ============================================================================\n// Immutable collection factories\n// ============================================================================\n\n/**\n * This function makes an immutable List from the given elements.\n *\n * @example\n * const list = immutableListOf(1, 2, 3)\n * list.get(0) // 1\n * list.add(4) // Error: Cannot modify readonly collection\n */\nexport function immutableListOf<T>(...elements: T[]): List<T> {\n if (elements.length === 0) {\n return emptyList<T>();\n }\n if (elements.length === 1) {\n return singletonList(elements[0]! as T);\n }\n const list = arrayList(elements);\n return compose(readonly<List<T>>())(list);\n}\n\n/**\n * This function makes an immutable Map from the given entries.\n */\nexport function immutableMapOf<K, V>(...entries: [K, V][]): MapLike<K, V> {\n if (entries.length === 0) {\n return emptyMap<K, V>();\n }\n if (entries.length === 1) {\n return singletonMap(entries[0]![0], entries[0]![1]);\n }\n const map = hashMap(entries);\n return compose(readonly<MapLike<K, V>>())(map);\n}\n\n// ============================================================================\n// Range factories\n// ============================================================================\n\n/**\n * This function makes a list containing integers from start (inclusive) to end (exclusive).\n *\n * @example\n * const list = range(0, 5) // [0, 1, 2, 3, 4]\n * const list2 = range(10, 15) // [10, 11, 12, 13, 14]\n */\nexport function range(start: number, end: number, step: number = 1): ArrayList<number> {\n if (step === 0) {\n throw new Error(\"step cannot be zero\");\n }\n\n const list = arrayList<number>();\n\n if (step > 0) {\n for (let i = start; i < end; i += step) {\n list.add(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n list.add(i);\n }\n }\n\n return list;\n}\n\n/**\n * This function makes a list containing integers from 0 to n (exclusive).\n *\n * @example\n * const list = rangeTo(5) // [0, 1, 2, 3, 4]\n */\nexport function rangeTo(n: number): ArrayList<number> {\n return range(0, n);\n}\n\n// ============================================================================\n// Collection builders\n// ============================================================================\n\n/**\n * Builder for constructing lists with a fluent API.\n *\n * @example\n * const list = buildList<number>((builder) => {\n * builder.add(1)\n * builder.add(2)\n * if (someCondition) {\n * builder.add(3)\n * }\n * })\n */\nexport function buildList<T>(builder: (list: ArrayList<T>) => void): ArrayList<T> {\n const list = arrayList<T>();\n builder(list);\n return list;\n}\n\n/**\n * Builder for constructing maps with a fluent API.\n */\nexport function buildMap<K, V>(builder: (map: HashMap<K, V>) => void): HashMap<K, V> {\n const map = hashMap<K, V>();\n builder(map);\n return map;\n}\n\n// ============================================================================\n// Conversion utilities\n// ============================================================================\n\n/**\n * This function converts an iterable to an ArrayList.\n *\n * @example\n * const set = new Set([1, 2, 3])\n * const list = toList(set)\n */\nexport function toList<T>(iterable: Iterable<T>): ArrayList<T> {\n return arrayList(iterable);\n}\n\n/**\n * This function converts an iterable to a HashMap using a key extractor function.\n *\n * @example\n * const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]\n * const userMap = toMap(users, u => u.id)\n */\nexport function toMap<T, K>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K\n): HashMap<K, T>;\nexport function toMap<T, K, V>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K,\n valueExtractor: (value: T) => V\n): HashMap<K, V>;\nexport function toMap<T, K, V>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K,\n valueExtractor?: (value: T) => V\n): HashMap<K, any> {\n const map = hashMap<K, any>();\n for (const item of iterable) {\n const key = keyExtractor(item);\n const value = valueExtractor ? valueExtractor(item) : item;\n map.set(key, value);\n }\n return map;\n}\n\n// ============================================================================\n// Grouping utilities\n// ============================================================================\n\n/**\n * This function groups elements by a key extractor function.\n *\n * @example\n * const users = [\n * { age: 25, name: 'Alice' },\n * { age: 30, name: 'Bob' },\n * { age: 25, name: 'Charlie' }\n * ]\n * const byAge = groupBy(users, u => u.age)\n * // Map { 25 => [Alice, Charlie], 30 => [Bob] }\n */\nexport function groupBy<T, K>(\n iterable: Iterable<T>,\n keyExtractor: (value: T) => K\n): HashMap<K, ArrayList<T>> {\n const map = hashMap<K, ArrayList<T>>();\n\n for (const item of iterable) {\n const key = keyExtractor(item);\n const list = map.computeIfAbsent(key, () => arrayList<T>());\n list.add(item);\n }\n\n return map;\n}\n","/**\n * Common helper utilities for collections.\n *\n * This module gives shared functionality to reduce code duplication across implementations.\n */\n\nimport type { Eq } from \"../core/traits.js\";\n\n// ============================================================================\n// Bounds checking utilities\n// ============================================================================\n\n/**\n * This function gives true when an index is in the bounds [0, size).\n * This function throws RangeError if out of bounds.\n *\n * @param index The index to check\n * @param size The size of the collection\n * @param collectionName Optional name for error message\n * @throws RangeError if index is out of bounds\n */\nexport function checkBounds(index: number, size: number, collectionName: string = \"Collection\"): void {\n if (index < 0 || index >= size) {\n throw new RangeError(`${collectionName}: Index ${index} out of bounds [0, ${size})`);\n }\n}\n\n/**\n * This function gives true when an index is valid for an insertion, in [0, size].\n * In this function, index === size is correct for append operations.\n *\n * @param index The index to check\n * @param size The size of the collection\n * @param collectionName Optional name for error message\n * @throws RangeError if index is out of bounds\n */\nexport function checkInsertBounds(index: number, size: number, collectionName: string = \"Collection\"): void {\n if (index < 0 || index > size) {\n throw new RangeError(`${collectionName}: Index ${index} out of bounds [0, ${size}]`);\n }\n}\n\n/**\n * This function gives true when a range [start, end) is valid.\n *\n * @param start Start index (inclusive)\n * @param end End index (exclusive)\n * @param size The size of the collection\n * @param collectionName Optional name for error message\n * @throws RangeError if range is invalid\n */\nexport function checkRangeBounds(\n start: number,\n end: number,\n size: number,\n collectionName: string = \"Collection\"\n): void {\n if (start < 0 || end > size || start > end) {\n throw new RangeError(\n `${collectionName}: Invalid range [${start}, ${end}) for size ${size}`\n );\n }\n}\n\n// ============================================================================\n// Equality and search utilities\n// ============================================================================\n\n/**\n * This function finds the index of an element in an array using custom equality.\n *\n * @param array The array to search\n * @param element The element to find\n * @param eq Equality function\n * @returns Index of element, or -1 if not found\n */\nexport function findIndex<T>(array: T[], element: T, eq: Eq<T>): number {\n for (let i = 0; i < array.length; i++) {\n if (eq(array[i]!, element)) {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * This function finds the last index of an element in an array using custom equality.\n *\n * @param array The array to search\n * @param element The element to find\n * @param eq Equality function\n * @returns Last index of element, or -1 if not found\n */\nexport function findLastIndex<T>(array: T[], element: T, eq: Eq<T>): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (eq(array[i]!, element)) {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * This function gives true when an array has an element, with a custom equality.\n *\n * @param array The array to search\n * @param element The element to find\n * @param eq Equality function\n * @returns true if element is found\n */\nexport function arrayContains<T>(array: T[], element: T, eq: Eq<T>): boolean {\n return findIndex(array, element, eq) !== -1;\n}\n\n/**\n * This function removes the first occurrence of an element from an array.\n *\n * @param array The array to change\n * @param element The element to remove\n * @param eq Equality function\n * @returns true if element was found and removed\n */\nexport function arrayRemove<T>(array: T[], element: T, eq: Eq<T>): boolean {\n const index = findIndex(array, element, eq);\n if (index === -1) return false;\n array.splice(index, 1);\n return true;\n}\n\n/**\n * This function removes all occurrences of an element from an array.\n *\n * @param array The array to change\n * @param element The element to remove\n * @param eq Equality function\n * @returns Number of elements removed\n */\nexport function arrayRemoveAll<T>(array: T[], element: T, eq: Eq<T>): number {\n let count = 0;\n for (let i = array.length - 1; i >= 0; i--) {\n if (eq(array[i]!, element)) {\n array.splice(i, 1);\n count++;\n }\n }\n return count;\n}\n\n// ============================================================================\n// Iterator utilities\n// ============================================================================\n\n/**\n * This function makes a simple iterator for an array.\n *\n * @param array The array to iterate\n * @returns Iterator over the array\n */\nexport function* arrayIterator<T>(array: T[]): Iterator<T> {\n yield* array;\n}\n\n/**\n * This function makes a reversed iterator for an array.\n *\n * @param array The array to iterate\n * @returns Reversed iterator over the array\n */\nexport function* reverseArrayIterator<T>(array: T[]): Iterator<T> {\n for (let i = array.length - 1; i >= 0; i--) {\n yield array[i]!;\n }\n}\n\n/**\n * This function converts an iterable to an array.\n *\n * @param iterable The iterable to convert\n * @returns Array containing all elements\n */\nexport function toArray<T>(iterable: Iterable<T>): T[] {\n return Array.from(iterable);\n}\n\n// ============================================================================\n// Validation utilities\n// ============================================================================\n\n/**\n * This function makes sure that a value is not null or undefined.\n *\n * @param value The value to check\n * @param message Error message\n * @returns The non-null value\n * @throws Error if value is null or undefined\n */\nexport function requireNonNull<T>(value: T | null | undefined, message: string = \"Value cannot be null or undefined\"): T {\n if (value === null || value === undefined) {\n throw new Error(message);\n }\n return value;\n}\n\n/**\n * This function makes sure that a collection is not empty.\n *\n * @param size Current size\n * @param collectionName Optional name for error message\n * @throws Error if collection is empty\n */\nexport function requireNonEmpty(size: number, collectionName: string = \"Collection\"): void {\n if (size === 0) {\n throw new Error(`${collectionName} is empty`);\n }\n}\n\n// ============================================================================\n// Math utilities\n// ============================================================================\n\n/**\n * This function clamps a value between min and max.\n *\n * @param value The value to clamp\n * @param min Minimum value\n * @param max Maximum value\n * @returns Clamped value\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * This function calculates hash code for a string.\n * This function uses Java's String.hashCode() algorithm.\n *\n * @param str The string to hash\n * @returns Hash code\n */\nexport function stringHashCode(str: string): number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return hash;\n}\n"],"mappings":";;;;;;;AAmRA,MAAa,0BAA0C;;;;AAKvD,MAAa,2BAA4C;;;;AAKzD,MAAa,0BAA0C;;;;AAKvD,MAAa,uBAAoC;CAC/C,aAAa;CACb,cAAc;CACd,SAAS;CACT,UAAU;CACV,QAAQ;AACV;;;;AAKA,MAAa,0BACX;;;;AAKF,MAAa,wBAAsC;CACjD,UAAU;CACV,aAAa,OAAO;AACtB;;;;AAKA,MAAa,4BAA8C;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1P3D,SAAgB,QAA0C,GAAG,QAAkC;CAC7F,OAAOA,UAAK,GAAI,MAA2B;AAC7C;;;;;;;;;;;AAYA,MAAa,iBACX,YACA,eACyC;CACzC,OAAO,cAAc;AACvB;;;;;;;;;;;;;AAsFA,MAAa,oBACX,QACA,gBACM;CACN,OAAO,IAAI,MAAM,QAAQ,EACvB,IAAI,GAAG,MAAM,UAAU;EACrB,MAAM,QAAQ,QAAQ,IAAI,GAAG,MAAM,QAAQ;EAC3C,IAAI,OAAO,UAAU,cAAc,OAAO,SAAS,UACjD,OAAO,SAAyB,GAAG,MAAiB;GAClD,OAAO,YAAY,GAAG,MAAiB,IAAI;EAC7C;EAEF,OAAO;CACT,EACF,CAAC;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