@mark1russell7/collections 0.1.0 → 0.3.0

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.
@@ -11,6 +11,15 @@ export declare function show(value: unknown): string;
11
11
  /**
12
12
  * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
13
13
  * are equal when they have the same keys with equal values, in any order.
14
+ *
15
+ * This function is for JSON values in tests. It is not `deepEq`, the equality of the collections,
16
+ * and it differs in these cases:
17
+ *
18
+ * - A `Date`, a `Set` or an instance of a class equals only itself here. So `new Date(0)` does not
19
+ * equal `new Date(0)` here, and it does under `deepEq`.
20
+ * - 0 does not equal -0 here, and it does under `deepEq`.
21
+ * - `{}` equals `Object.create(null)` here, and it does not under `deepEq`.
22
+ * - A cyclic value exhausts the stack here, and it ends under `deepEq`.
14
23
  */
15
24
  export declare function deepEqual(actual: unknown, expected: unknown): boolean;
16
25
  /** This function throws `ContractViolation` when the two values are not deeply equal. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/testing/check.ts"],"mappings":";;;;;qBAMa,0BAA0B;oBACnB;;;wBAIJ,KAAK;;;;;wBAmBL,UAAU,iBAAiB;;wBAqB3B,KAAK,iBAAiB,mBAAmB;;wBAOzC,MAAM,oBAAoB;;;;;wBAQpB,QAAQ,aAAa,kBAAkB,eAAe"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/testing/check.ts"],"mappings":";;;;;qBAMa,0BAA0B;oBACnB;;;wBAIJ,KAAK;;;;;;;;;;;;;;wBA4BL,UAAU,iBAAiB;;wBAqB3B,KAAK,iBAAiB,mBAAmB;;wBAOzC,MAAM,oBAAoB;;;;;wBAQpB,QAAQ,aAAa,kBAAkB,eAAe"}
@@ -24,6 +24,15 @@ function isPlainObject(value) {
24
24
  /**
25
25
  * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
26
26
  * are equal when they have the same keys with equal values, in any order.
27
+ *
28
+ * This function is for JSON values in tests. It is not `deepEq`, the equality of the collections,
29
+ * and it differs in these cases:
30
+ *
31
+ * - A `Date`, a `Set` or an instance of a class equals only itself here. So `new Date(0)` does not
32
+ * equal `new Date(0)` here, and it does under `deepEq`.
33
+ * - 0 does not equal -0 here, and it does under `deepEq`.
34
+ * - `{}` equals `Object.create(null)` here, and it does not under `deepEq`.
35
+ * - A cyclic value exhausts the stack here, and it ends under `deepEq`.
27
36
  */
28
37
  function deepEqual(actual, expected) {
29
38
  if (Object.is(actual, expected)) return true;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/testing/check.ts"],"sourcesContent":["/**\n * The checks of the contract suite. The suite does not import a test framework, so a runtime\n * entry of this package does not load one. A failed check throws `ContractViolation`.\n */\n\n/** The error of a failed check of the contract suite. */\nexport class ContractViolation extends Error {\n override readonly name = \"ContractViolation\";\n}\n\n/** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */\nexport function show(value: unknown): string {\n if (value === undefined) return \"undefined\";\n try {\n return JSON.stringify(value, (_key, item: unknown) => (item instanceof Map ? { Map: [...item.entries()] } : item === undefined ? \"<undefined>\" : item));\n } catch {\n return String(value);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps\n * are equal when they have the same keys with equal values, in any order.\n */\nexport function deepEqual(actual: unknown, expected: unknown): boolean {\n if (Object.is(actual, expected)) return true;\n if (actual instanceof Map && expected instanceof Map) {\n if (actual.size !== expected.size) return false;\n for (const [key, value] of actual) {\n if (!expected.has(key) || !deepEqual(value, expected.get(key))) return false;\n }\n return true;\n }\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length && actual.every((item, index) => deepEqual(item, expected[index]));\n }\n if (isPlainObject(actual) && isPlainObject(expected)) {\n const keys = Object.keys(actual);\n if (keys.length !== Object.keys(expected).length) return false;\n return keys.every((key) => Object.prototype.hasOwnProperty.call(expected, key) && deepEqual(actual[key], expected[key]));\n }\n return false;\n}\n\n/** This function throws `ContractViolation` when the two values are not deeply equal. */\nexport function same(actual: unknown, expected: unknown, what: string): void {\n if (!deepEqual(actual, expected)) {\n throw new ContractViolation(`${what}: expected ${show(expected)}, got ${show(actual)}`);\n }\n}\n\n/** This function throws `ContractViolation` when the condition is false. */\nexport function holds(condition: boolean, what: string): void {\n if (!condition) throw new ContractViolation(what);\n}\n\n/**\n * This function starts an operation that must fail with a rejected promise, and gives the error.\n * A synchronous throw breaks the contract too: each method of a storage gives a promise.\n */\nexport async function rejects(start: () => Promise<unknown>, what: string): Promise<unknown> {\n let promise: Promise<unknown>;\n try {\n promise = start();\n } catch (error) {\n throw new ContractViolation(`${what}: the method threw at once (${show(error instanceof Error ? error.message : error)}), and did not give a rejected promise`);\n }\n holds(typeof promise?.then === \"function\", `${what}: the method did not give a promise`);\n try {\n await promise;\n } catch (error) {\n return error;\n }\n throw new ContractViolation(`${what}: the promise did not reject`);\n}\n"],"mappings":";;;;;;AAMA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,OAAyB;AAC3B;;AAGA,SAAgB,KAAK,OAAwB;CAC3C,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI;EACF,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAmB,gBAAgB,MAAM,EAAE,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,EAAE,IAAI,SAAS,KAAA,IAAY,gBAAgB,IAAK;CACxJ,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;;;;AAMA,SAAgB,UAAU,QAAiB,UAA4B;C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AAG,KAAK,oCAAoC;CACvF,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,OAAO;CACT;CACA,MAAM,IAAI,kBAAkB,GAAG,KAAK,6BAA6B;AACnE"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/testing/check.ts"],"sourcesContent":["/**\n * The checks of the contract suite. The suite does not import a test framework, so a runtime\n * entry of this package does not load one. A failed check throws `ContractViolation`.\n */\n\n/** The error of a failed check of the contract suite. */\nexport class ContractViolation extends Error {\n override readonly name = \"ContractViolation\";\n}\n\n/** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */\nexport function show(value: unknown): string {\n if (value === undefined) return \"undefined\";\n try {\n return JSON.stringify(value, (_key, item: unknown) => (item instanceof Map ? { Map: [...item.entries()] } : item === undefined ? \"<undefined>\" : item));\n } catch {\n return String(value);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps\n * are equal when they have the same keys with equal values, in any order.\n *\n * This function is for JSON values in tests. It is not `deepEq`, the equality of the collections,\n * and it differs in these cases:\n *\n * - A `Date`, a `Set` or an instance of a class equals only itself here. So `new Date(0)` does not\n * equal `new Date(0)` here, and it does under `deepEq`.\n * - 0 does not equal -0 here, and it does under `deepEq`.\n * - `{}` equals `Object.create(null)` here, and it does not under `deepEq`.\n * - A cyclic value exhausts the stack here, and it ends under `deepEq`.\n */\nexport function deepEqual(actual: unknown, expected: unknown): boolean {\n if (Object.is(actual, expected)) return true;\n if (actual instanceof Map && expected instanceof Map) {\n if (actual.size !== expected.size) return false;\n for (const [key, value] of actual) {\n if (!expected.has(key) || !deepEqual(value, expected.get(key))) return false;\n }\n return true;\n }\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length && actual.every((item, index) => deepEqual(item, expected[index]));\n }\n if (isPlainObject(actual) && isPlainObject(expected)) {\n const keys = Object.keys(actual);\n if (keys.length !== Object.keys(expected).length) return false;\n return keys.every((key) => Object.prototype.hasOwnProperty.call(expected, key) && deepEqual(actual[key], expected[key]));\n }\n return false;\n}\n\n/** This function throws `ContractViolation` when the two values are not deeply equal. */\nexport function same(actual: unknown, expected: unknown, what: string): void {\n if (!deepEqual(actual, expected)) {\n throw new ContractViolation(`${what}: expected ${show(expected)}, got ${show(actual)}`);\n }\n}\n\n/** This function throws `ContractViolation` when the condition is false. */\nexport function holds(condition: boolean, what: string): void {\n if (!condition) throw new ContractViolation(what);\n}\n\n/**\n * This function starts an operation that must fail with a rejected promise, and gives the error.\n * A synchronous throw breaks the contract too: each method of a storage gives a promise.\n */\nexport async function rejects(start: () => Promise<unknown>, what: string): Promise<unknown> {\n let promise: Promise<unknown>;\n try {\n promise = start();\n } catch (error) {\n throw new ContractViolation(`${what}: the method threw at once (${show(error instanceof Error ? error.message : error)}), and did not give a rejected promise`);\n }\n holds(typeof promise?.then === \"function\", `${what}: the method did not give a promise`);\n try {\n await promise;\n } catch (error) {\n return error;\n }\n throw new ContractViolation(`${what}: the promise did not reject`);\n}\n"],"mappings":";;;;;;AAMA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,OAAyB;AAC3B;;AAGA,SAAgB,KAAK,OAAwB;CAC3C,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI;EACF,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAmB,gBAAgB,MAAM,EAAE,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,EAAE,IAAI,SAAS,KAAA,IAAY,gBAAgB,IAAK;CACxJ,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;;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AAuC;CAChK;CACA,MAAM,OAAO,SAAS,SAAS,YAAY,GAAG,KAAK,oCAAoC;CACvF,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,OAAO;CACT;CACA,MAAM,IAAI,kBAAkB,GAAG,KAAK,6BAA6B;AACnE"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/collections",
4
- "version": "0.1.0",
4
+ "version": "0.3.0",
5
5
  "description": "Collections with no dependencies: lists, maps, queues, a summary tree, channels, lazy operations and dependency graphs.",
6
6
  "keywords": [
7
7
  "collections",
@@ -27,6 +27,15 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
27
27
  /**
28
28
  * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
29
29
  * are equal when they have the same keys with equal values, in any order.
30
+ *
31
+ * This function is for JSON values in tests. It is not `deepEq`, the equality of the collections,
32
+ * and it differs in these cases:
33
+ *
34
+ * - A `Date`, a `Set` or an instance of a class equals only itself here. So `new Date(0)` does not
35
+ * equal `new Date(0)` here, and it does under `deepEq`.
36
+ * - 0 does not equal -0 here, and it does under `deepEq`.
37
+ * - `{}` equals `Object.create(null)` here, and it does not under `deepEq`.
38
+ * - A cyclic value exhausts the stack here, and it ends under `deepEq`.
30
39
  */
31
40
  export function deepEqual(actual: unknown, expected: unknown): boolean {
32
41
  if (Object.is(actual, expected)) return true;
@@ -39,37 +39,142 @@ export const shallowEq: Eq<any> = (a, b) => {
39
39
  return true;
40
40
  };
41
41
 
42
+ /** SameValueZero: the meaning of `===`, and NaN equals NaN. */
43
+ const sameValueZero = (a: unknown, b: unknown): boolean => a === b || (Number.isNaN(a) && Number.isNaN(b));
44
+
45
+ const isObject = (value: unknown): value is object => typeof value === "object" && value !== null;
46
+
47
+ /** The pairs that one comparison holds equal. The log lets a failed try remove its pairs. */
48
+ interface HeldPairs {
49
+ readonly partners: Map<object, Set<object>>;
50
+ readonly log: [object, object][];
51
+ }
52
+
53
+ function releasePairs(held: HeldPairs, mark: number): void {
54
+ while (held.log.length > mark) {
55
+ const [a, b] = held.log.pop()!;
56
+ held.partners.get(a)?.delete(b);
57
+ }
58
+ }
59
+
60
+ function equalElements(a: ArrayLike<unknown>, b: ArrayLike<unknown>): boolean {
61
+ if (a.length !== b.length) return false;
62
+ for (let i = 0; i < a.length; i++) {
63
+ if (!sameValueZero(a[i], b[i])) return false;
64
+ }
65
+ return true;
66
+ }
67
+
68
+ /** The kinds of `equalObjects` and `hashFields`, so that the relation and its hash stay in step. */
69
+ const isBinary = (value: object): value is ArrayBufferLike | DataView =>
70
+ value instanceof DataView || value instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer);
71
+
72
+ const isOpaque = (value: object): boolean => value instanceof Promise || value instanceof WeakMap || value instanceof WeakSet || value instanceof WeakRef;
73
+
74
+ const isBoxed = (value: object): boolean =>
75
+ value instanceof Number || value instanceof String || value instanceof Boolean || value instanceof BigInt || value instanceof Symbol;
76
+
77
+ function bytesOf(value: ArrayBufferLike | DataView): Uint8Array {
78
+ return ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value);
79
+ }
80
+
81
+ function enumerableKeys(value: object): (string | symbol)[] {
82
+ return Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));
83
+ }
84
+
85
+ function equalKeys(a: any, b: any, held: HeldPairs): boolean {
86
+ const keys = enumerableKeys(a);
87
+ if (keys.length !== enumerableKeys(b).length) return false;
88
+ return keys.every((key) => Object.prototype.propertyIsEnumerable.call(b, key) && equalValues(a[key], b[key], held));
89
+ }
90
+
42
91
  /**
43
- * Deep structural equality (recursive comparison).
44
- * This function handles nested objects and arrays.
92
+ * The comparison of the entries of two maps, or of the members of two sets. A primitive key finds
93
+ * its partner by `has`. An object key tries each object key of `b` that is not taken yet. The first
94
+ * partner is correct, because the relation is an equivalence.
45
95
  */
46
- export const deepEq: Eq<any> = (a, b): boolean => {
47
- if (a === b) return true;
48
- if (typeof a !== typeof b) return false;
49
- if (typeof a !== "object" || a === null || b === null) return false;
96
+ function equalEntries(a: Map<unknown, unknown> | Set<unknown>, b: Map<unknown, unknown> | Set<unknown>, held: HeldPairs): boolean {
97
+ if (a.size !== b.size) return false;
98
+ const valueAt = (key: unknown): unknown => (b instanceof Map ? b.get(key) : key);
99
+ const free = [...b.entries()].filter(([key]) => isObject(key));
100
+ for (const [key, value] of a.entries()) {
101
+ if (!isObject(key)) {
102
+ if (!b.has(key) || !equalValues(value, valueAt(key), held)) return false;
103
+ continue;
104
+ }
105
+ const at = free.findIndex(([otherKey, otherValue]) => {
106
+ const mark = held.log.length;
107
+ if (equalValues(key, otherKey, held) && equalValues(value, otherValue, held)) return true;
108
+ releasePairs(held, mark);
109
+ return false;
110
+ });
111
+ if (at < 0) return false;
112
+ free.splice(at, 1);
113
+ }
114
+ return true;
115
+ }
50
116
 
51
- if (Array.isArray(a) && Array.isArray(b)) {
52
- if (a.length !== b.length) return false;
117
+ /** The comparison of two objects with the same prototype. */
118
+ function equalObjects(a: any, b: any, held: HeldPairs): boolean {
119
+ if (Array.isArray(a) || Array.isArray(b)) {
120
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
53
121
  for (let i = 0; i < a.length; i++) {
54
- if (!deepEq(a[i], b[i])) return false;
122
+ if (!equalValues(a[i], b[i], held)) return false;
55
123
  }
56
124
  return true;
57
125
  }
126
+ if (isBinary(a)) return equalElements(bytesOf(a), bytesOf(b));
127
+ if (ArrayBuffer.isView(a)) return equalElements(a as unknown as ArrayLike<unknown>, b);
128
+ if (isOpaque(a)) return false;
129
+ if (a instanceof Date && !sameValueZero(a.getTime(), b.getTime())) return false;
130
+ if (a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags)) return false;
131
+ if (a instanceof Error && !(a.name === b.name && a.message === b.message && equalValues(a.cause, b.cause, held))) return false;
132
+ if (isBoxed(a) && !sameValueZero(a.valueOf(), b.valueOf())) return false;
133
+ if ((a instanceof Map || a instanceof Set) && !equalEntries(a, b, held)) return false;
134
+ return equalKeys(a, b, held);
135
+ }
58
136
 
59
- if (Array.isArray(a) !== Array.isArray(b)) return false;
60
-
61
- const keysA = Object.keys(a);
62
- const keysB = Object.keys(b);
63
-
64
- if (keysA.length !== keysB.length) return false;
65
-
66
- for (const key of keysA) {
67
- if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
68
- if (!deepEq(a[key], b[key])) return false;
137
+ /**
138
+ * The comparison of two values. A pair stays held after it passes, so a shared or cyclic part
139
+ * costs one visit. A failure ends the whole comparison, or the try in `equalEntries`, which
140
+ * releases its pairs.
141
+ */
142
+ function equalValues(a: unknown, b: unknown, held: HeldPairs): boolean {
143
+ if (sameValueZero(a, b)) return true;
144
+ if (!isObject(a) || !isObject(b)) return false;
145
+ if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
146
+ let partners = held.partners.get(a);
147
+ if (partners?.has(b)) return true;
148
+ if (partners === undefined) {
149
+ partners = new Set();
150
+ held.partners.set(a, partners);
69
151
  }
152
+ partners.add(b);
153
+ held.log.push([a, b]);
154
+ return equalObjects(a, b, held);
155
+ }
70
156
 
71
- return true;
72
- };
157
+ /**
158
+ * Deep structural equality. This relation is an equivalence: it is reflexive, symmetric and
159
+ * transitive, for each value.
160
+ *
161
+ * - Primitives compare by SameValueZero: NaN equals NaN, and 0 equals -0.
162
+ * - Two objects must have the same prototype. So `{}` differs from `Object.create(null)`, from an
163
+ * instance of a class with the same keys, and from an object of another realm.
164
+ * - Arrays compare by length and by index. A hole equals `undefined`.
165
+ * - Typed arrays compare by element. `ArrayBuffer`, `SharedArrayBuffer` and `DataView` compare by byte.
166
+ * - `Date` compares by time, `RegExp` by source and flags, and `Error` by name, message and cause.
167
+ * - A boxed primitive compares by its value. `Map` and `Set` compare by entries, in any order. An object key
168
+ * matches a deep-equal key.
169
+ * - Each other object compares by its own enumerable keys, strings and symbols, in any order. The objects above do too,
170
+ * except arrays and binary data.
171
+ * - Functions, `Promise`, `WeakMap`, `WeakSet` and `WeakRef` compare by identity.
172
+ * - Cycles are safe: two cyclic values are equal when they unfold to the same infinite tree.
173
+ *
174
+ * The recursion follows the depth of the data, so a very deep value can exhaust the stack.
175
+ * `defaultHash` agrees with this relation: two equal values have one hash.
176
+ */
177
+ export const deepEq: Eq<any> = (a, b): boolean => equalValues(a, b, { partners: new Map(), log: [] });
73
178
 
74
179
  /**
75
180
  * Equality by comparing a specific property.
@@ -90,17 +195,11 @@ export const eqBy = <T, K extends keyof T = keyof T>(
90
195
  // Default Hashing
91
196
  // ============================================================================
92
197
 
93
- /**
94
- * Default hash function for primitives and objects.
95
- * For objects, hashes the JSON string representation.
96
- */
97
- export const defaultHash: Hash<any> = (value: any): number => {
198
+ /** The hash of one primitive or function. */
199
+ function hashPrimitive(value: unknown): number {
98
200
  if (value === null) return 0;
99
201
  if (value === undefined) return 1;
100
-
101
- const type = typeof value;
102
-
103
- switch (type) {
202
+ switch (typeof value) {
104
203
  case "boolean":
105
204
  return value ? 1 : 0;
106
205
  case "number":
@@ -111,19 +210,104 @@ export const defaultHash: Hash<any> = (value: any): number => {
111
210
  return hashString(value.toString());
112
211
  case "bigint":
113
212
  return hashString(value.toString());
114
- case "object":
115
- // For objects, hash their JSON representation
116
- // This is not ideal for all cases but provides a reasonable default
117
- try {
118
- return hashString(JSON.stringify(value));
119
- } catch {
120
- // If JSON.stringify fails, fall back to toString
121
- return hashString(value.toString());
122
- }
123
213
  default:
124
214
  return 2;
125
215
  }
126
- };
216
+ }
217
+
218
+ /** The levels of an object that `defaultHash` reads. A cyclic value unfolds to this depth and stops. */
219
+ const HASH_DEPTH = 16;
220
+
221
+ /** The hashes of one call, by object and by remaining depth. A shared part costs one visit per depth. */
222
+ type HashMemo = Map<object, number[]>;
223
+
224
+ /** This function adds one hash to a running hash. The result depends on the order. */
225
+ const mix = (hash: number, part: number): number => (Math.imul(hash, 31) + part) | 0;
226
+
227
+ /** The finalizer of MurmurHash3. It makes a sum of entries depend on each pair, not on each half. */
228
+ function scramble(hash: number): number {
229
+ let mixed = hash ^ (hash >>> 16);
230
+ mixed = Math.imul(mixed, 0x85ebca6b);
231
+ mixed ^= mixed >>> 13;
232
+ mixed = Math.imul(mixed, 0xc2b2ae35);
233
+ return mixed ^ (mixed >>> 16);
234
+ }
235
+
236
+ /** The start values of the kinds. Two kinds do not compare equal, so their hashes can differ. */
237
+ const KIND = { array: 3, binary: 5, elements: 7, opaque: 11, record: 13 } as const;
238
+
239
+ const hashAt = (value: unknown, depth: number, memo: HashMemo): number =>
240
+ isObject(value) ? hashObject(value, depth, memo) : hashPrimitive(value);
241
+
242
+ function hashElements(start: number, elements: ArrayLike<unknown>): number {
243
+ let hash = start;
244
+ for (let i = 0; i < elements.length; i++) hash = mix(hash, hashPrimitive(elements[i]));
245
+ return hash;
246
+ }
247
+
248
+ /** The sum of the entries of a map or a set. A sum does not depend on the order of the entries. */
249
+ function hashEntries(value: Map<unknown, unknown> | Set<unknown>, depth: number, memo: HashMemo): number {
250
+ let sum = 0;
251
+ for (const [key, entry] of value.entries()) sum = (sum + scramble(mix(hashAt(key, depth, memo), hashAt(entry, depth, memo)))) | 0;
252
+ return sum;
253
+ }
254
+
255
+ /** The sum of the own enumerable keys and their values, as `equalKeys` reads them. */
256
+ function hashKeys(value: any, depth: number, memo: HashMemo): number {
257
+ let sum = 0;
258
+ for (const key of enumerableKeys(value)) sum = (sum + scramble(mix(hashPrimitive(key), hashAt(value[key], depth, memo)))) | 0;
259
+ return sum;
260
+ }
261
+
262
+ /** The hash of the fields of one object. This function reads only what `equalObjects` reads. */
263
+ function hashFields(value: any, depth: number, memo: HashMemo): number {
264
+ if (Array.isArray(value)) {
265
+ let hash: number = KIND.array;
266
+ for (let i = 0; i < value.length; i++) hash = mix(hash, hashAt(value[i], depth, memo));
267
+ return hash;
268
+ }
269
+ if (isBinary(value)) return hashElements(KIND.binary, bytesOf(value));
270
+ if (ArrayBuffer.isView(value)) return hashElements(KIND.elements, value as unknown as ArrayLike<unknown>);
271
+ if (isOpaque(value)) return KIND.opaque;
272
+ let hash: number = KIND.record;
273
+ if (value instanceof Date) hash = mix(hash, hashNumber(value.getTime()));
274
+ if (value instanceof RegExp) hash = mix(mix(hash, hashString(value.source)), hashString(value.flags));
275
+ if (value instanceof Error) {
276
+ hash = mix(mix(mix(hash, hashAt(value.name, depth, memo)), hashAt(value.message, depth, memo)), hashAt(value.cause, depth, memo));
277
+ }
278
+ if (isBoxed(value)) hash = mix(hash, hashPrimitive(value.valueOf()));
279
+ if (value instanceof Map || value instanceof Set) hash = mix(hash, hashEntries(value, depth, memo));
280
+ return mix(hash, hashKeys(value, depth, memo));
281
+ }
282
+
283
+ /** The hash of one object at one depth. The depth falls with each level, so a cycle ends. */
284
+ function hashObject(value: object, depth: number, memo: HashMemo): number {
285
+ if (depth === 0) return 0;
286
+ let byDepth = memo.get(value);
287
+ if (byDepth === undefined) {
288
+ byDepth = [];
289
+ memo.set(value, byDepth);
290
+ }
291
+ const known = byDepth[depth];
292
+ if (known !== undefined) return known;
293
+ const hash = hashFields(value, depth - 1, memo);
294
+ byDepth[depth] = hash;
295
+ return hash;
296
+ }
297
+
298
+ /**
299
+ * This function is the default hash of a key. It agrees with `deepEq`: when `deepEq(a, b)` is true,
300
+ * `defaultHash(a)` equals `defaultHash(b)`. So a hash map with `deepEq` finds an equal key.
301
+ *
302
+ * - The hash of an object reads the same fields as `deepEq`. The order of the keys of an object,
303
+ * and of the entries of a `Map` or a `Set`, has no effect.
304
+ * - The hash reads 16 levels, so a cyclic or very deep value ends. Two values that differ only
305
+ * below that depth have one hash, and `deepEq` then tells them apart.
306
+ * - A shared part costs one visit per level, so a dense graph ends.
307
+ * - The hash of an object can change in a new version. Do not store it.
308
+ */
309
+ export const defaultHash: Hash<any> = (value: any): number =>
310
+ isObject(value) ? hashObject(value, HASH_DEPTH, new Map()) : hashPrimitive(value);
127
311
 
128
312
  /**
129
313
  * Hash function for strings using djb2 algorithm.