@mark1russell7/collections 0.2.0 → 0.4.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.
@@ -0,0 +1,59 @@
1
+ /**
2
+ * This module holds the one fold of a stack of layers. A layer wraps the next thing, so a stack
3
+ * of layers wraps a base. The next thing can be a collection, a function or any other value.
4
+ *
5
+ * This file has no imports. A package that needs only the fold loads this one file.
6
+ *
7
+ * @example
8
+ * const parse = compose(
9
+ * (next: (text: string) => number) => (text: string) => next(text.trim()),
10
+ * (next: (text: string) => number) => (text: string) => next(text) * 2
11
+ * )(Number);
12
+ * parse(" 21 "); // 42
13
+ */
14
+ /**
15
+ * A layer takes the next thing and gives a wrapped thing.
16
+ *
17
+ * @template Inner The type that the layer wraps
18
+ * @template Outer The type that the layer gives
19
+ */
20
+ type Layer<Inner = any, Outer = Inner> = (next: Inner) => Outer;
21
+ /** This type gives the type that a layer wraps. */
22
+ type InnerOf<L> = L extends ((next: infer I) => any) ? I : never;
23
+ /** This type gives the type that a layer gives. */
24
+ type OuterOf<L> = L extends ((next: any) => infer O) ? O : never;
25
+ /**
26
+ * This type checks each neighbor pair of a list of layers. The result of the inner neighbor must
27
+ * fit the input of the outer neighbor. At the first bad pair, the compiler marks that argument.
28
+ *
29
+ * The type is tail recursive, so the compiler accepts a chain of 100 layers.
30
+ */
31
+ type Chain<L extends readonly unknown[], Done extends readonly unknown[] = readonly []> = L extends readonly [infer A, infer B, ...infer R] ? [OuterOf<B>] extends [InnerOf<A>] ? Chain<readonly [B, ...R], readonly [...Done, A]> : readonly [...Done, A, Layer<any, InnerOf<A>>, ...R] : readonly [...Done, ...L];
32
+ /**
33
+ * This type gives the function that {@link compose} returns. Its input is the input of the last
34
+ * layer, and its result is the result of the first layer. No layers give the identity function.
35
+ * A list that the compiler cannot see as a tuple gives the types of one element.
36
+ */
37
+ type Composed<L extends readonly unknown[]> = L extends readonly [] ? <B>(base: B) => B : L extends readonly [infer First, ...unknown[]] ? L extends readonly [...unknown[], infer Last] ? (base: InnerOf<Last>) => OuterOf<First> : never : L extends readonly (infer E)[] ? (base: InnerOf<E>) => OuterOf<E> : never;
38
+ /** This type gives the intersection of the results of a list of layers. */
39
+ type Outers<L extends readonly unknown[], Sum = unknown> = L extends readonly [infer First, ...infer Rest] ? Outers<Rest, Sum & OuterOf<First>> : Sum;
40
+ /**
41
+ * This type gives the function for layers that keep each capability of the layers under them.
42
+ * Its result has the result of each layer and the base. Use it only when that law holds.
43
+ */
44
+ type Stacked<L extends readonly unknown[]> = L extends readonly [...unknown[], infer Last] ? (base: InnerOf<Last>) => Outers<L> & InnerOf<Last> : Composed<L>;
45
+ /**
46
+ * This function folds layers into one function that wraps a base. The first layer is the outermost.
47
+ *
48
+ * The fold holds four laws:
49
+ * - Identity: `compose()(b)` is `b`.
50
+ * - One layer: `compose(f)(b)` is `f(b)`.
51
+ * - Associativity: `compose(f, compose(g, h))` equals `compose(compose(f, g), h)`.
52
+ * - Order: `compose(f, g)(b)` is `f(g(b))`.
53
+ *
54
+ * @param layers The layers, from the outermost to the innermost
55
+ * @returns A function that wraps a base in the layers
56
+ */
57
+ declare function compose<const L extends readonly Layer[]>(...layers: L & Chain<L>): Composed<L>;
58
+ export { OuterOf as a, compose as c, Layer as i, Composed as n, Outers as o, InnerOf as r, Stacked as s, Chain as t };
59
+ //# sourceMappingURL=layers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layers.d.ts","names":[],"sources":["../src/core/layers.ts"],"mappings":";;;;;;;;;;;;;;;;;;;KAoBY,MAAM,aAAa,QAAQ,UAAU,MAAM,UAAU;;KAGrD,QAAQ,KAAK,YAAW,YAAY,aAAY;;KAGhD,QAAQ,KAAK,YAAW,oBAAoB,KAAI;;;;;;;KAQhD,MAAM,8BAA8B,iDAC9C,0BAA0B,SAAS,YAAY,MAC1C,QAAQ,aAAa,QAAQ,MAC5B,gBAAgB,MAAM,iBAAiB,MAAM,mBAChC,MAAM,GAAG,WAAW,QAAQ,QAAQ,kBACtC,SAAS;;;;;;KAOhB,SAAS,gCACnB,yBACK,GAAG,MAAM,MAAM,IAChB,0BAA0B,uBACxB,wCAAwC,SACrC,MAAM,QAAQ,UAAU,QAAQ,iBAEnC,0BAA0B,QACvB,MAAM,QAAQ,OAAO,QAAQ;;KAI5B,OAAO,8BAA8B,iBAC/C,0BAA0B,gBAAgB,QAAQ,OAAO,MAAM,MAAM,QAAQ,UAAU;;;;;KAM7E,QAAQ,gCAClB,wCAAwC,SACnC,MAAM,QAAQ,UAAU,OAAO,KAAK,QAAQ,QAC7C,SAAS;;;;;;;;;;;;;iBAcC,cAAc,mBAAmB,YAAY,QAAQ,IAAI,MAAM,KAAK,SAAS"}
@@ -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,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;AAGA,SAAgB,MAAM,WAAoB,MAAoB;CAC5D,IAAI,CAAC,WAAW,MAAM,IAAI,kBAAkB,IAAI;AAClD;;;;;AAMA,eAAsB,QAAQ,OAA+B,MAAgC;CAC3F,IAAI;CACJ,IAAI;EACF,UAAU,MAAM;CAClB,SAAS,OAAO;EACd,MAAM,IAAI,kBAAkB,GAAG,KAAK,8BAA8B,KAAK,iBAAiB,QAAQ,MAAM,UAAU,KAAK,EAAE,uCAAuC;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"}
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,KAA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K,QAAQ,EAAE,QAAQ,KAAK,MAAM,GAAG;AAE1F;;AAGA,SAAgB,MAAM,WAAoB,MAAoB;CAC5D,IAAI,CAAC,WAAW,MAAM,IAAI,kBAAkB,IAAI;AAClD;;;;;AAMA,eAAsB,QAAQ,OAA+B,MAAgC;CAC3F,IAAI;CACJ,IAAI;EACF,UAAU,MAAM;CAClB,SAAS,OAAO;EACd,MAAM,IAAI,kBAAkB,GAAG,KAAK,8BAA8B,KAAK,iBAAiB,QAAQ,MAAM,UAAU,KAAK,EAAE,uCAAuC;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.4.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",
@@ -43,6 +43,10 @@
43
43
  "types": "./build/graph/index.d.ts",
44
44
  "default": "./build/graph/index.js"
45
45
  },
46
+ "./layers": {
47
+ "types": "./build/core/layers.d.ts",
48
+ "default": "./build/core/layers.js"
49
+ },
46
50
  "./testing": {
47
51
  "types": "./build/testing/index.d.ts",
48
52
  "default": "./build/testing/index.js"
@@ -64,6 +68,9 @@
64
68
  },
65
69
  "devDependencies": {
66
70
  "@mark1russell7/cue": "^2.0.0",
71
+ "@mark1russell7/rigor-bench": "^0.2.5",
72
+ "@mark1russell7/rigor-generators": "^0.1.5",
73
+ "@mark1russell7/rigor-statistics": "^0.1.8",
67
74
  "@types/node": "^26.6.5",
68
75
  "esbuild": "^0.28.2",
69
76
  "fast-check": "^4.10.2",
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @example
8
8
  * const list = compose(
9
- * boundedList({ capacity: 100, policy: 'drop-oldest' })
9
+ * boundedList<number>({ capacity: 100, policy: 'drop-oldest' })
10
10
  * )(arrayList<number>())
11
11
  *
12
12
  * // Add 101 elements - first element will be dropped
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @example
8
8
  * const list = compose(
9
- * eventedList()
9
+ * eventedList<number>()
10
10
  * )(arrayList<number>())
11
11
  *
12
12
  * list.on('add', ({ value, index }) => {
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @example
8
8
  * const cache = compose(
9
- * lruMap({ capacity: 100 })
9
+ * lruMap<string, Data>({ capacity: 100 })
10
10
  * )(hashMap<string, Data>())
11
11
  *
12
12
  * cache.set('key1', data1) // Accessed
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @example
8
8
  * const list = compose(
9
- * safeList()
9
+ * safeList<number>()
10
10
  * )(arrayList<number>())
11
11
  *
12
12
  * const value = list.safe.get(10) // Option<number> instead of throwing
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @example
8
8
  * const cache = compose(
9
- * ttlMap({ ttl: 60000 }) // 60 seconds
9
+ * ttlMap<string, Data>({ ttl: 60000 }) // 60 seconds
10
10
  * )(hashMap<string, Data>())
11
11
  *
12
12
  * cache.set('key', data)
@@ -0,0 +1,86 @@
1
+ /**
2
+ * This module holds the one fold of a stack of layers. A layer wraps the next thing, so a stack
3
+ * of layers wraps a base. The next thing can be a collection, a function or any other value.
4
+ *
5
+ * This file has no imports. A package that needs only the fold loads this one file.
6
+ *
7
+ * @example
8
+ * const parse = compose(
9
+ * (next: (text: string) => number) => (text: string) => next(text.trim()),
10
+ * (next: (text: string) => number) => (text: string) => next(text) * 2
11
+ * )(Number);
12
+ * parse(" 21 "); // 42
13
+ */
14
+
15
+ /**
16
+ * A layer takes the next thing and gives a wrapped thing.
17
+ *
18
+ * @template Inner The type that the layer wraps
19
+ * @template Outer The type that the layer gives
20
+ */
21
+ export type Layer<Inner = any, Outer = Inner> = (next: Inner) => Outer;
22
+
23
+ /** This type gives the type that a layer wraps. */
24
+ export type InnerOf<L> = L extends (next: infer I) => any ? I : never;
25
+
26
+ /** This type gives the type that a layer gives. */
27
+ export type OuterOf<L> = L extends (next: any) => infer O ? O : never;
28
+
29
+ /**
30
+ * This type checks each neighbor pair of a list of layers. The result of the inner neighbor must
31
+ * fit the input of the outer neighbor. At the first bad pair, the compiler marks that argument.
32
+ *
33
+ * The type is tail recursive, so the compiler accepts a chain of 100 layers.
34
+ */
35
+ export type Chain<L extends readonly unknown[], Done extends readonly unknown[] = readonly []> =
36
+ L extends readonly [infer A, infer B, ...infer R]
37
+ ? [OuterOf<B>] extends [InnerOf<A>]
38
+ ? Chain<readonly [B, ...R], readonly [...Done, A]>
39
+ : readonly [...Done, A, Layer<any, InnerOf<A>>, ...R]
40
+ : readonly [...Done, ...L];
41
+
42
+ /**
43
+ * This type gives the function that {@link compose} returns. Its input is the input of the last
44
+ * layer, and its result is the result of the first layer. No layers give the identity function.
45
+ * A list that the compiler cannot see as a tuple gives the types of one element.
46
+ */
47
+ export type Composed<L extends readonly unknown[]> =
48
+ L extends readonly []
49
+ ? <B>(base: B) => B
50
+ : L extends readonly [infer First, ...unknown[]]
51
+ ? L extends readonly [...unknown[], infer Last]
52
+ ? (base: InnerOf<Last>) => OuterOf<First>
53
+ : never
54
+ : L extends readonly (infer E)[]
55
+ ? (base: InnerOf<E>) => OuterOf<E>
56
+ : never;
57
+
58
+ /** This type gives the intersection of the results of a list of layers. */
59
+ export type Outers<L extends readonly unknown[], Sum = unknown> =
60
+ L extends readonly [infer First, ...infer Rest] ? Outers<Rest, Sum & OuterOf<First>> : Sum;
61
+
62
+ /**
63
+ * This type gives the function for layers that keep each capability of the layers under them.
64
+ * Its result has the result of each layer and the base. Use it only when that law holds.
65
+ */
66
+ export type Stacked<L extends readonly unknown[]> =
67
+ L extends readonly [...unknown[], infer Last]
68
+ ? (base: InnerOf<Last>) => Outers<L> & InnerOf<Last>
69
+ : Composed<L>;
70
+
71
+ /**
72
+ * This function folds layers into one function that wraps a base. The first layer is the outermost.
73
+ *
74
+ * The fold holds four laws:
75
+ * - Identity: `compose()(b)` is `b`.
76
+ * - One layer: `compose(f)(b)` is `f(b)`.
77
+ * - Associativity: `compose(f, compose(g, h))` equals `compose(compose(f, g), h)`.
78
+ * - Order: `compose(f, g)(b)` is `f(g(b))`.
79
+ *
80
+ * @param layers The layers, from the outermost to the innermost
81
+ * @returns A function that wraps a base in the layers
82
+ */
83
+ export function compose<const L extends readonly Layer[]>(...layers: L & Chain<L>): Composed<L> {
84
+ const list: readonly Layer[] = layers;
85
+ return ((base: unknown) => list.reduceRight((acc, layer) => layer(acc), base)) as Composed<L>;
86
+ }
@@ -9,13 +9,14 @@
9
9
  *
10
10
  * @example
11
11
  * const list = compose(
12
- * safeList(),
13
- * eventedList(),
14
- * boundedList({ capacity: 100 })
12
+ * safeList<number>(),
13
+ * eventedList<number>(),
14
+ * boundedList<number>({ capacity: 100 })
15
15
  * )(arrayList<number>())
16
16
  */
17
17
 
18
18
  import type { Collection } from "../interfaces/collection.js";
19
+ import { compose as fold, type Chain, type Layer, type Stacked } from "./layers.js";
19
20
 
20
21
  /**
21
22
  * A middleware is a function that takes a collection and gives
@@ -52,9 +53,9 @@ export type Middleware<In = any, Out extends In = In> = (next: In) => Out;
52
53
  * // 3. bounded - enforces capacity limits
53
54
  * // 4. base - the underlying ArrayList
54
55
  * const enhancer = compose(
55
- * safeList(),
56
- * eventedList(),
57
- * boundedList({ capacity: 100 })
56
+ * safeList<number>(),
57
+ * eventedList<number>(),
58
+ * boundedList<number>({ capacity: 100 })
58
59
  * )
59
60
  * const list = enhancer(arrayList<number>())
60
61
  * // Type: List<number> & SafeCollection & EventedCollection & BoundedCollection
@@ -62,49 +63,8 @@ export type Middleware<In = any, Out extends In = In> = (next: In) => Out;
62
63
  * @param layers The middleware layers to compose
63
64
  * @returns A function that applies all layers to a base collection
64
65
  */
65
-
66
- // Overload for 1 middleware
67
- export function compose<C, R1 extends C>(
68
- m1: Middleware<C, R1>
69
- ): (base: C) => R1;
70
-
71
- // Overload for 2 middleware
72
- export function compose<C, R1 extends C, R2 extends R1>(
73
- m1: Middleware<R1, R2>,
74
- m2: Middleware<C, R1>
75
- ): (base: C) => R2;
76
-
77
- // Overload for 3 middleware
78
- export function compose<C, R1 extends C, R2 extends R1, R3 extends R2>(
79
- m1: Middleware<R2, R3>,
80
- m2: Middleware<R1, R2>,
81
- m3: Middleware<C, R1>
82
- ): (base: C) => R3;
83
-
84
- // Overload for 4 middleware
85
- export function compose<C, R1 extends C, R2 extends R1, R3 extends R2, R4 extends R3>(
86
- m1: Middleware<R3, R4>,
87
- m2: Middleware<R2, R3>,
88
- m3: Middleware<R1, R2>,
89
- m4: Middleware<C, R1>
90
- ): (base: C) => R4;
91
-
92
- // Overload for 5 middleware
93
- export function compose<C, R1 extends C, R2 extends R1, R3 extends R2, R4 extends R3, R5 extends R4>(
94
- m1: Middleware<R4, R5>,
95
- m2: Middleware<R3, R4>,
96
- m3: Middleware<R2, R3>,
97
- m4: Middleware<R1, R2>,
98
- m5: Middleware<C, R1>
99
- ): (base: C) => R5;
100
-
101
- // General fallback for any number of middleware
102
- export function compose<C>(...layers: Middleware<any, any>[]): (base: C) => any;
103
-
104
- // Implementation
105
- export function compose(...layers: Middleware<any, any>[]) {
106
- return (base: any): any =>
107
- layers.reduceRight((acc, layer) => layer(acc), base);
66
+ export function compose<const L extends readonly Layer[]>(...layers: L & Chain<L>): Stacked<L> {
67
+ return fold(...(layers as readonly Layer[])) as unknown as Stacked<L>;
108
68
  }
109
69
 
110
70
  /**
@@ -361,53 +321,11 @@ export const enhanceMethod = <C extends object, K extends keyof C & string>(
361
321
  *
362
322
  * @example
363
323
  * const standardBehaviors = bundle(
364
- * boundedList({ capacity: 1000 }),
365
- * eventedList(),
366
- * safeList()
324
+ * boundedList<number>({ capacity: 1000 }),
325
+ * eventedList<number>(),
326
+ * safeList<number>()
367
327
  * )
368
328
  *
369
329
  * const list = compose(standardBehaviors)(arrayList<number>())
370
330
  */
371
-
372
- // Overload for 1 middleware
373
- export function bundle<C, R1 extends C>(
374
- m1: Middleware<C, R1>
375
- ): Middleware<C, R1>;
376
-
377
- // Overload for 2 middleware
378
- export function bundle<C, R1 extends C, R2 extends R1>(
379
- m1: Middleware<R1, R2>,
380
- m2: Middleware<C, R1>
381
- ): Middleware<C, R2>;
382
-
383
- // Overload for 3 middleware
384
- export function bundle<C, R1 extends C, R2 extends R1, R3 extends R2>(
385
- m1: Middleware<R2, R3>,
386
- m2: Middleware<R1, R2>,
387
- m3: Middleware<C, R1>
388
- ): Middleware<C, R3>;
389
-
390
- // Overload for 4 middleware
391
- export function bundle<C, R1 extends C, R2 extends R1, R3 extends R2, R4 extends R3>(
392
- m1: Middleware<R3, R4>,
393
- m2: Middleware<R2, R3>,
394
- m3: Middleware<R1, R2>,
395
- m4: Middleware<C, R1>
396
- ): Middleware<C, R4>;
397
-
398
- // Overload for 5 middleware
399
- export function bundle<C, R1 extends C, R2 extends R1, R3 extends R2, R4 extends R3, R5 extends R4>(
400
- m1: Middleware<R4, R5>,
401
- m2: Middleware<R3, R4>,
402
- m3: Middleware<R2, R3>,
403
- m4: Middleware<R1, R2>,
404
- m5: Middleware<C, R1>
405
- ): Middleware<C, R5>;
406
-
407
- // General fallback for any number of middleware
408
- export function bundle<C>(...middleware: Middleware<any, any>[]): Middleware<C, any>;
409
-
410
- // Implementation
411
- export function bundle(...middleware: Middleware<any, any>[]): Middleware<any, any> {
412
- return (next: any): any => compose(...middleware)(next);
413
- }
331
+ export const bundle: typeof compose = compose;
@@ -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.