@mark1russell7/collections 0.2.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.2.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;
@@ -65,6 +65,15 @@ function equalElements(a: ArrayLike<unknown>, b: ArrayLike<unknown>): boolean {
65
65
  return true;
66
66
  }
67
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
+
68
77
  function bytesOf(value: ArrayBufferLike | DataView): Uint8Array {
69
78
  return ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value);
70
79
  }
@@ -114,16 +123,13 @@ function equalObjects(a: any, b: any, held: HeldPairs): boolean {
114
123
  }
115
124
  return true;
116
125
  }
117
- if (a instanceof DataView || a instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && a instanceof SharedArrayBuffer)) {
118
- return equalElements(bytesOf(a), bytesOf(b));
119
- }
126
+ if (isBinary(a)) return equalElements(bytesOf(a), bytesOf(b));
120
127
  if (ArrayBuffer.isView(a)) return equalElements(a as unknown as ArrayLike<unknown>, b);
121
- if (a instanceof Promise || a instanceof WeakMap || a instanceof WeakSet || a instanceof WeakRef) return false;
128
+ if (isOpaque(a)) return false;
122
129
  if (a instanceof Date && !sameValueZero(a.getTime(), b.getTime())) return false;
123
130
  if (a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags)) return false;
124
131
  if (a instanceof Error && !(a.name === b.name && a.message === b.message && equalValues(a.cause, b.cause, held))) return false;
125
- const boxed = a instanceof Number || a instanceof String || a instanceof Boolean || a instanceof BigInt || a instanceof Symbol;
126
- if (boxed && !sameValueZero(a.valueOf(), b.valueOf())) return false;
132
+ if (isBoxed(a) && !sameValueZero(a.valueOf(), b.valueOf())) return false;
127
133
  if ((a instanceof Map || a instanceof Set) && !equalEntries(a, b, held)) return false;
128
134
  return equalKeys(a, b, held);
129
135
  }
@@ -166,6 +172,7 @@ function equalValues(a: unknown, b: unknown, held: HeldPairs): boolean {
166
172
  * - Cycles are safe: two cyclic values are equal when they unfold to the same infinite tree.
167
173
  *
168
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.
169
176
  */
170
177
  export const deepEq: Eq<any> = (a, b): boolean => equalValues(a, b, { partners: new Map(), log: [] });
171
178
 
@@ -188,17 +195,11 @@ export const eqBy = <T, K extends keyof T = keyof T>(
188
195
  // Default Hashing
189
196
  // ============================================================================
190
197
 
191
- /**
192
- * Default hash function for primitives and objects.
193
- * For objects, hashes the JSON string representation.
194
- */
195
- export const defaultHash: Hash<any> = (value: any): number => {
198
+ /** The hash of one primitive or function. */
199
+ function hashPrimitive(value: unknown): number {
196
200
  if (value === null) return 0;
197
201
  if (value === undefined) return 1;
198
-
199
- const type = typeof value;
200
-
201
- switch (type) {
202
+ switch (typeof value) {
202
203
  case "boolean":
203
204
  return value ? 1 : 0;
204
205
  case "number":
@@ -209,19 +210,104 @@ export const defaultHash: Hash<any> = (value: any): number => {
209
210
  return hashString(value.toString());
210
211
  case "bigint":
211
212
  return hashString(value.toString());
212
- case "object":
213
- // For objects, hash their JSON representation
214
- // This is not ideal for all cases but provides a reasonable default
215
- try {
216
- return hashString(JSON.stringify(value));
217
- } catch {
218
- // If JSON.stringify fails, fall back to toString
219
- return hashString(value.toString());
220
- }
221
213
  default:
222
214
  return 2;
223
215
  }
224
- };
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);
225
311
 
226
312
  /**
227
313
  * Hash function for strings using djb2 algorithm.