// ets_tracing: off import "../../../Operator/index.js" import type { Refinement } from "../../../Function/index.js" import { constant, identity, tuple } from "../../../Function/index.js" import { NoSuchElementException } from "../../../GlobalExceptions/index.js" import * as I from "../../../Iterable/index.js" import * as O from "../../../Option/index.js" import * as St from "../../../Structural/index.js" import * as Tp from "../Tuple/index.js" import { fromBitmap, hashFragment, toBitmap } from "./Bitwise/index.js" import { SIZE } from "./Config/index.js" import type { Node, UpdateFn } from "./Nodes/index.js" import { Empty, isEmptyNode } from "./Nodes/index.js" const HashMapHash = St.hashString("HashMap") export class HashMap implements Iterable { readonly _K!: () => K readonly _V!: () => V constructor( public editable: boolean, public edit: number, public root: Node, public size: number ) {} [Symbol.iterator](): Iterator { return new HashMapIterator(this, identity) } readonly tupleIterator: Iterable> = { [Symbol.iterator]: () => new HashMapIterator(this, ([k, v]) => Tp.tuple(k, v)) } get [St.hashSym](): number { let hash = HashMapHash for (const item of this) { hash ^= St.combineHash(St.hashUnknown(item[0]), St.hashUnknown(item[1])) } return hash } [St.equalsSym](that: unknown): boolean { if (that instanceof HashMap) { if (that.size !== this.size) { return false } for (const item of this) { const elem = getHash_(that, item[0], St.hash(item[0])) if (elem._tag === "None") { return false } else { if (!St.equals(item[1], elem.value)) { return false } } } return true } return false } } export class HashMapIterator implements IterableIterator { v = visitLazy(this.map.root, this.f, undefined) constructor(readonly map: HashMap, readonly f: TraversalFn) {} next(): IteratorResult { if (O.isNone(this.v)) { return { done: true, value: undefined } } const v0 = this.v.value this.v = applyCont(v0.cont) return { done: false, value: v0.value } } [Symbol.iterator](): IterableIterator { return new HashMapIterator(this.map, this.f) } } /** * Creates a new map */ export function make() { return new HashMap(false, 0, new Empty(), 0) } /** * Creates a new map from an Iterable */ export function from(xs: Iterable): HashMap { return I.reduce_(xs, make(), (m, p) => set_(m, ...p)) } /** * Set the root of the map */ export function setTree_( map: HashMap, newRoot: Node, newSize: number ) { if (map.editable) { map.root = newRoot map.size = newSize return map } return newRoot === map.root ? map : new HashMap(map.editable, map.edit, newRoot, newSize) } /** * Lookup the value for `key` in `map` using custom hash. */ export function tryGetHash_( map: HashMap, key: K, hash: number ): O.Option { let node = map.root let shift = 0 // eslint-disable-next-line no-constant-condition while (true) switch (node._tag) { case "LeafNode": { return St.equals(key, node.key) ? node.value : O.none } case "CollisionNode": { if (hash === node.hash) { const children = node.children for (let i = 0, len = children.length; i < len; ++i) { const child = children[i]! if ("key" in child && St.equals(key, child.key)) return child.value } } return O.none } case "IndexedNode": { const frag = hashFragment(shift, hash) const bit = toBitmap(frag) if (node.mask & bit) { node = node.children[fromBitmap(node.mask, bit)]! shift += SIZE break } return O.none } case "ArrayNode": { node = node.children[hashFragment(shift, hash)]! if (node) { shift += SIZE break } return O.none } default: return O.none } } /** * Lookup the value for `key` in `map` using custom hash. */ export function getHash_(map: HashMap, key: K, hash: number): O.Option { return tryGetHash_(map, key, hash) } /** * Lookup the value for `key` in `map` using internal hash function. */ export function unsafeGet_(map: HashMap, key: K): V { const element = tryGetHash_(map, key, St.hash(key)) if (O.isNone(element)) { throw new NoSuchElementException() } return element.value } /** * Lookup the value for `key` in `map` using internal hash function. * * @ets_data_first unsafeGet_ */ export function unsafeGet(key: K) { return (map: HashMap) => unsafeGet_(map, key) } /** * Lookup the value for `key` in `map` using internal hash function. */ export function get_(map: HashMap, key: K): O.Option { return tryGetHash_(map, key, St.hash(key)) } /** * Lookup the value for `key` in `map` using internal hash function. * * @ets_data_first get_ */ export function get(key: K) { return (map: HashMap) => get_(map, key) } /** * Does an entry exist for `key` in `map`? Uses custom `hash`. */ export function hasHash_(map: HashMap, key: K, hash: number): boolean { return O.isSome(tryGetHash_(map, key, hash)) } /** * Does an entry exist for `key` in `map`? Uses internal hash function. */ export function has_(map: HashMap, key: K): boolean { return O.isSome(tryGetHash_(map, key, St.hash(key))) } /** * Does an entry exist for `key` in `map`? Uses internal hash function. * * @ets_data_first has_ */ export function has(key: K) { return (map: HashMap) => has_(map, key) } /** * Does `map` contain any elements? */ export function isEmpty(map: HashMap): boolean { return map && !!isEmptyNode(map.root) } /** * Alter the value stored for `key` in `map` using function `f` using custom hash. * * `f` is invoked with the current value for `k` if it exists, * or no arguments if no such value exists. * * `modify` will always either update or insert a value into the map. * Returns a map with the modified value. Does not alter `map`. */ export function modifyHash_( map: HashMap, key: K, hash: number, f: UpdateFn ): HashMap { const size = { value: map.size } const newRoot = map.root.modify(map.editable ? map.edit : NaN, 0, f, hash, key, size) return setTree_(map, newRoot, size.value) } /** * Alter the value stored for `key` in `map` using function `f` using internal hash function. * * `f` is invoked with the current value for `k` if it exists, * or no arguments if no such value exists. * * `modify` will always either update or insert a value into the map. * Returns a map with the modified value. Does not alter `map`. */ export function modify_(map: HashMap, key: K, f: UpdateFn) { return modifyHash_(map, key, St.hash(key), f) } /** * Alter the value stored for `key` in `map` using function `f` using internal hash function. * * `f` is invoked with the current value for `k` if it exists, * or no arguments if no such value exists. * * `modify` will always either update or insert a value into the map. * Returns a map with the modified value. Does not alter `map`. * * @ets_data_first modify_ */ export function modify(key: K, f: UpdateFn) { return (map: HashMap) => modify_(map, key, f) } /** * Store `value` for `key` in `map` using internal hash function. */ export function set_(map: HashMap, key: K, value: V) { return modify_(map, key, constant(O.some(value))) } /** * Store `value` for `key` in `map` using internal hash function. * * @ets_data_first set_ */ export function set(key: K, value: V) { return (map: HashMap) => set_(map, key, value) } /** * Remove the entry for `key` in `map` using internal hash. */ export function remove_(map: HashMap, key: K) { return modify_(map, key, constant(O.none)) } /** * Remove the entry for `key` in `map` using internal hash. * * @ets_data_first remove_ */ export function remove(key: K) { return (map: HashMap) => remove_(map, key) } /** * Mark `map` as mutable. */ export function beginMutation(map: HashMap) { return new HashMap(true, map.edit + 1, map.root, map.size) } /** * Mark `map` as immutable. */ export function endMutation(map: HashMap) { map.editable = false return map } /** * Mutate `map` within the context of `f`. * * @ets_data_first mutate_ */ export function mutate(f: (map: HashMap) => void) { return (map: HashMap) => mutate_(map, f) } /** * Mutate `map` within the context of `f`. */ export function mutate_(map: HashMap, f: (map: HashMap) => void) { const transient = beginMutation(map) f(transient) return endMutation(transient) } export type Cont = | [ len: number, children: Node[], i: number, f: TraversalFn, cont: Cont ] | undefined export function applyCont(cont: Cont) { return cont ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4]) : O.none } export function visitLazyChildren( len: number, children: Node[], i: number, f: TraversalFn, cont: Cont ): O.Option> { while (i < len) { const child = children[i++] if (child && !isEmptyNode(child)) { return visitLazy(child, f, [len, children, i, f, cont]) } } return applyCont(cont) } export interface VisitResult { value: A cont: Cont } export type TraversalFn = (node: readonly [K, V]) => A /** * Visit each leaf lazily */ export function visitLazy( node: Node, f: TraversalFn, cont: Cont = undefined ): O.Option> { switch (node._tag) { case "LeafNode": { return O.isSome(node.value) ? O.some({ value: f(tuple(node.key, node.value.value)), cont }) : applyCont(cont) } case "CollisionNode": case "ArrayNode": case "IndexedNode": { const children = node.children return visitLazyChildren(children.length, children, 0, f, cont) } default: { return applyCont(cont) } } } /** * Get an IterableIterator of the map keys */ export function keys(map: HashMap): IterableIterator { return new HashMapIterator(map, ([k]) => k) } /** * Get an IterableIterator of the map values */ export function values(map: HashMap): IterableIterator { return new HashMapIterator(map, ([, v]) => v) } /** * Update a value if exists */ export function update_(map: HashMap, key: K, f: (v: V) => V) { return modify_(map, key, O.map(f)) } /** * Update a value if exists * * @ets_data_first update_ */ export function update(key: K, f: (v: V) => V) { return (map: HashMap) => update_(map, key, f) } /** * Reduce a state over the map entries */ export function reduceWithIndex_( map: HashMap, z: Z, f: (z: Z, k: K, v: V) => Z ): Z { const root = map.root if (root._tag === "LeafNode") return O.isSome(root.value) ? f(z, root.key, root.value.value) : z if (root._tag === "Empty") { return z } const toVisit = [root.children] let children while ((children = toVisit.pop())) { for (let i = 0, len = children.length; i < len; ) { const child = children[i++] if (child && !isEmptyNode(child)) { if (child._tag === "LeafNode") { if (O.isSome(child.value)) { z = f(z, child.key, child.value.value) } } else toVisit.push(child.children) } } } return z } /** * Reduce a state over the map entries * * @ets_data_first reduceWithIndex_ */ export function reduceWithIndex(z: Z, f: (z: Z, k: K, v: V) => Z) { return (map: HashMap) => reduceWithIndex_(map, z, f) } /** * Reduce a state over the map entries */ export function reduce_(map: HashMap, z: Z, f: (z: Z, v: V) => Z): Z { return reduceWithIndex_(map, z, (z, _, v) => f(z, v)) } /** * Reduce a state over the map entries * * @ets_data_first reduce_ */ export function reduce(z: Z, f: (z: Z, v: V) => Z) { return (map: HashMap) => reduce_(map, z, f) } /** * Apply f to each element */ export function forEachWithIndex_(map: HashMap, f: (k: K, v: V) => void) { reduceWithIndex_(map, undefined as void, (_, key, value) => f(key, value)) } /** * Apply f to each element * * @ets_data_first forEachWithIndex_ */ export function forEachWithIndex(f: (k: K, v: V) => void) { return (map: HashMap) => forEachWithIndex_(map, f) } /** * Apply f to each element */ export function forEach_(map: HashMap, f: (v: V) => void) { forEachWithIndex_(map, (_, value) => f(value)) } /** * Apply f to each element * * @ets_data_first forEach_ */ export function forEach(f: (v: V) => void) { return (map: HashMap) => forEach_(map, f) } /** * Maps over the map entries */ export function mapWithIndex_(map: HashMap, f: (k: K, v: V) => A) { return reduceWithIndex_(map, make(), (z, k, v) => set_(z, k, f(k, v))) } /** * Maps over the map entries * * @ets_data_first mapWithIndex_ */ export function mapWithIndex(f: (k: K, v: V) => A) { return (map: HashMap) => mapWithIndex_(map, f) } /** * Maps over the map entries */ export function map_(map: HashMap, f: (v: V) => A) { return reduceWithIndex_(map, make(), (z, k, v) => set_(z, k, f(v))) } /** * Maps over the map entries * * @ets_data_first map_ */ export function map(f: (v: V) => A) { return (map: HashMap) => map_(map, f) } /** * Chain over the map entries, the hash and equal of the 2 maps has to be the same */ export function chain_(map: HashMap, f: (v: V) => HashMap) { return reduceWithIndex_(map, make(), (z, _, v) => mutate_(z, (m) => { forEachWithIndex_(f(v), (_k, _a) => { set_(m, _k, _a) }) }) ) } /** * Chain over the map entries, the hash and equal of the 2 maps has to be the same * * @ets_data_first chain_ */ export function chain(f: (v: V) => HashMap) { return (map: HashMap) => chain_(map, f) } /** * Chain over the map entries, the hash and equal of the 2 maps has to be the same */ export function chainWithIndex_( map: HashMap, f: (k: K, v: V) => HashMap ) { return reduceWithIndex_(map, make(), (z, k, v) => mutate_(z, (m) => { forEachWithIndex_(f(k, v), (_k, _a) => { set_(m, _k, _a) }) }) ) } /** * Chain over the map entries, the hash and equal of the 2 maps has to be the same * * @ets_data_first chainWithIndex_ */ export function chainWithIndex(f: (k: K, v: V) => HashMap) { return (map: HashMap) => chainWithIndex_(map, f) } /** * Removes None values */ export function compact(fa: HashMap>): HashMap { return filterMapWithIndex_(fa, (_, a) => a) } /** * Filter out None and map */ export function filterMapWithIndex_( fa: HashMap, f: (k: K, a: A) => O.Option ): HashMap { const m = make() return mutate_(m, (m) => { for (const [k, a] of fa) { const o = f(k, a) if (O.isSome(o)) { set_(m, k, o.value) } } }) } /** * Filter out None and map * * @ets_data_first filterMapWithIndex_ */ export function filterMapWithIndex(f: (k: K, a: A) => O.Option) { return (fa: HashMap) => filterMapWithIndex_(fa, f) } /** * Filter out None and map */ export function filterMap_( fa: HashMap, f: (a: A) => O.Option ): HashMap { return filterMapWithIndex_(fa, (_, a) => f(a)) } /** * Filter out None and map * * @ets_data_first filterMap_ */ export function filterMap(f: (a: A) => O.Option) { return (fa: HashMap) => filterMap_(fa, f) } /** * Filter out by predicate */ export function filterWithIndex_( fa: HashMap, p: (k: K, a: A) => boolean ): HashMap { const m = make() return mutate_(m, (m) => { for (const [k, a] of fa) { if (p(k, a)) { set_(m, k, a) } } }) } /** * Filter out by predicate * * @ets_data_first filterWithIndex_ */ export function filterWithIndex(p: (k: K, a: A) => boolean) { return (fa: HashMap) => filterWithIndex_(fa, p) } /** * Filter out by predicate */ export function filter_( fa: HashMap, p: Refinement ): HashMap export function filter_(fa: HashMap, p: (a: A) => boolean): HashMap export function filter_(fa: HashMap, p: (a: A) => boolean): HashMap { return filterWithIndex_(fa, (_, a) => p(a)) } /** * Filter out by predicate * * @ets_data_first filter_ */ export function filter( p: Refinement ): (fa: HashMap) => HashMap export function filter( p: (a: A) => boolean ): (fa: HashMap) => HashMap { return (fa) => filter_(fa, p) } /** * Calculate the number of key/value pairs in a map */ export function size(map: HashMap) { return map.size } /** * Remove many keys */ export function removeMany_(self: HashMap, ks: Iterable): HashMap { return mutate_(self, (m) => { for (const k of ks) { remove_(m, k) } }) } /** * Remove many keys * * @ets_data_first removeMany_ */ export function removeMany(ks: Iterable) { return (self: HashMap) => removeMany_(self, ks) }