recursive-set 5.0.3 β†’ 7.0.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.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Christian Strerath
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Christian Strerath
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,186 +1,207 @@
1
- # RecursiveSet
2
-
3
- > **High-Performance ZFC Set Implementation for TypeScript**
4
- >
5
- > Mutable, strictly typed, and optimized for cache locality.
6
-
7
- [![MIT License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
8
- [![npm version](https://img.shields.io/npm/v/recursive-set.svg)](https://www.npmjs.com/package/recursive-set)
9
-
10
- ---
11
-
12
- ## πŸš€ What is this?
13
-
14
- A mathematical set implementation designed for **Theoretical Computer Science**, **SAT-Solvers**, and **Graph Theory**. Unlike native JavaScript `Set`, `RecursiveSet` enforces **Structural Equality** (ZFC semantics) and supports deep nesting.
15
-
16
- **v5.0.0 Update:** Now featuring **"Freeze-on-Hash"** lifecycle management.
17
- * **Safety First**: Sets automatically become **immutable** (frozen) once used as a key or member of another set. No more corrupted hash codes!
18
- * **High Performance**: Backed by **Sorted Arrays** and FNV-1a hashing. 5x - 10x faster than tree-based implementations for typical *N* < 1000.
19
- * **O(1) Equality Checks**: Aggressive caching allows for instant comparisons of deep structures.
20
-
21
- ---
22
-
23
- ## Features
24
-
25
- * **πŸ”’ Strict Structural Equality:** `{1, 2}` is equal to `{2, 1}`.
26
- * **❄️ Freeze-on-Hash:** Mutable during construction, immutable during usage. Prevents subtle reference bugs.
27
- * **πŸ“¦ Deeply Recursive:** Sets can contain Sets. Ideal for Power Sets.
28
- * **πŸ“ Tuples & Arrays:** Native support for `Tuple` class or standard JS Arrays `[a, b]` as elements.
29
- * **πŸ”’ Type Safe:** Fully strict TypeScript implementation. No `any` casts.
30
- * **πŸ›‘οΈ Deterministic:** Hashing is order-independent for Sets and order-dependent for Sequences.
31
-
32
- ---
33
-
34
- ## Installation
35
-
36
- ```bash
37
- npm install recursive-set
38
- ```
39
-
40
- ---
41
- ## Quickstart
42
-
43
- ### 1. Basic Usage
44
- ```typescript
45
- import { RecursiveSet, Tuple } from "recursive-set";
46
-
47
- // Sets of primitives
48
- const states = new RecursiveSet<string>();
49
- states.add("q0").add("q1");
50
-
51
- // Sets of Sets (Partitioning)
52
- const partition = new RecursiveSet<RecursiveSet<string>>();
53
- partition.add(states); // {{q0, q1}}
54
-
55
- // Tuples (Ordered Pairs / Edges)
56
- const edge = new Tuple("q0", "q1");
57
- // or simply: const edge = ["q0", "q1"];
58
-
59
- const transitions = new RecursiveSet<Tuple<[string, string]>>();
60
- transitions.add(edge);
61
-
62
- console.log(partition.toString()); // {{q0, q1}}
63
- ```
64
-
65
- ### 2. The Lifecycle (Mutable -> Frozen)
66
-
67
- **New in v5:** To ensure mathematical correctness, a set cannot be modified once it has been hashed (e.g., added to another set).
68
-
69
- ```typescript
70
- const A = new RecursiveSet(1, 2);
71
- const B = new RecursiveSet(A);
72
- // B hashes A to store it.
73
- // A is now FROZEN to ensure B's integrity.
74
-
75
- console.log(B.has(A)); // true
76
-
77
- try {
78
- A.add(3); // πŸ’₯ Throws Error: Cannot add() to a frozen RecursiveSet
79
- } catch (e) {
80
- console.log("A is immutable now!");
81
- }
82
-
83
- // Fix: Create a mutable copy ("Forking")
84
- const C = A.mutableCopy();
85
- C.add(3); // Works!
86
- ```
87
-
88
- ---
89
-
90
- ## API Reference
91
-
92
- ### Constructor
93
-
94
- ```typescript
95
- // Create empty or with initial elements
96
- // Elements are automatically sorted and deduplicated.
97
- new RecursiveSet<T>(...elements: T[])
98
- ```
99
-
100
-
101
- ### Methods
102
-
103
- **Lifecycle Management:**
104
- * `mutableCopy(): RecursiveSet<T>` – Creates a fresh, mutable clone of the set (O(N)). Use this if you need to modify a frozen set.
105
- * `clone(): RecursiveSet<T>` – Alias for mutableCopy.
106
-
107
- **Mutation:**
108
- * `add(element: T): this` – Insert element (O(N) worst case, O(1) append).
109
- * `remove(element: T): this` – Remove element.
110
- * `clear(): this` – Reset set.
111
-
112
- **Set Operations (Immutable results):**
113
- * `union(other: RecursiveSet<T>): RecursiveSet<T>` – $A \cup B$
114
- * `intersection(other: RecursiveSet<T>): RecursiveSet<T>` – $A \cap B$
115
- * `difference(other: RecursiveSet<T>): RecursiveSet<T>` – $A \setminus B$
116
- * `symmetricDifference(other: RecursiveSet<T>): RecursiveSet<T>` – $A \triangle B$
117
- * `powerset(): RecursiveSet<RecursiveSet<T>>` – $\mathcal{P}(A)$
118
- * `cartesianProduct<U>(other: RecursiveSet<U>): RecursiveSet<Tuple<[T, U]>>` – $A \times B$
119
-
120
- **Predicates (Fast):**
121
- * `has(element: T): boolean` – **O(log N)** lookup (Binary Search).
122
- * `equals(other: RecursiveSet<T>): boolean` – **O(1)** via Hash-Cache (usually).
123
- * `isSubset(other: RecursiveSet<T>): boolean` – Check if $A \subseteq B$.
124
- * `isSuperset(other: RecursiveSet<T>): boolean` – Check if $A \supseteq B$.
125
- * `isEmpty(): boolean` – Check if $|A| = 0$.
126
-
127
- **Properties:**
128
- * `size: number` – Cardinality.
129
- * `hashCode: number` – The cached hash. Accessing this property freezes the set.
130
- * `isFrozen: boolean` – Check if the set is read-only.
131
-
132
- ---
133
-
134
- ## Performance Notes
135
-
136
- **Why Sorted Arrays?**
137
- For sets with $N < 1000$ (common in logic puzzles, N-Queens, graphs), the overhead of allocating tree nodes (v2/v3) dominates runtime. Sorted Arrays exploit **CPU Cache Lines**.
138
-
139
- | Operation | Complexity | Real World (Small N) |
140
- | :--- | :--- | :--- |
141
- | **Lookup** | $O(\log N)$ | πŸš€ Instant |
142
- | **Equality** | $O(N)$ / $O(1)$* | ⚑ Instant (Hash Match) |
143
- | **Insert** | $O(N)$ | Fast (Native `splice` / `memmove`) |
144
- | **Iteration** | $O(N)$ | πŸš€ Native Array Speed |
145
-
146
- *\*Equality is O(1) if hashes differ (99% case), O(N) if hash collision occurs.*
147
-
148
- ---
149
-
150
- ## Breaking Changes in v5.0
151
-
152
- 1. **Freeze-on-Hash Semantics:** To guarantee mathematical correctness, sets now transition to an **immutable state** once their `hashCode` is computed (which happens automatically when added to another `RecursiveSet` or used as a Map key).
153
- * *Old Behavior:* Modifying a hashed set was possible but resulted in corrupted hash codes and lookup failures.
154
- * *New Behavior:* Calling `add()`, `remove()` or `clear()` on a hashed set throws an `Error`.
155
- * *Migration:* Use `mutableCopy()` to create a modifiable clone if you need to evolve a state that has already been stored.
156
-
157
- ---
158
-
159
- ## Contributing
160
-
161
- Contributions are welcome!
162
-
163
- ```bash
164
- git clone https://github.com/cstrerath/recursive-set.git
165
- npm install
166
- npm run build
167
- npx tsx test/test.ts
168
- npx tsx test/nqueens.ts
169
- ```
170
-
171
- ---
172
-
173
- ## License
174
-
175
- MIT License
176
- Β© 2025 Christian Strerath
177
-
178
- See [LICENSE](LICENSE) for details.
179
-
180
- ---
181
-
182
- ## Acknowledgments
183
-
184
- Inspired by:
185
- * Zermelo-Fraenkel set theory (ZFC)
186
- * Formal Language Theory requirements
1
+ # RecursiveSet
2
+
3
+ [![MIT License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
4
+ [![npm version](https://img.shields.io/npm/v/recursive-set.svg)](https://www.npmjs.com/package/recursive-set)
5
+
6
+ High-performance set implementation for TypeScript with **value semantics** (structural equality) and controlled mutability via β€œfreeze-on-hash”.
7
+
8
+ ## Overview
9
+
10
+ `RecursiveSet` is a mathematical set designed for workloads in theoretical computer science (SAT solvers, graph algorithms, ZFC-style constructions) where deep nesting and structural equality matter (e.g., `{1,2} = {2,1}`).
11
+
12
+ Key design points:
13
+
14
+ - Structural equality (ZFC-like semantics) for nested sets and sequences.
15
+ - Mutable during construction; becomes immutable once hashed (β€œfreeze-on-hash”).
16
+ - Sorted-array backing for good cache locality on small to medium `N`.
17
+ - Bulk loading and merge-scan set operations for speed.
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install recursive-set
23
+ ```
24
+
25
+
26
+ ## Quickstart
27
+
28
+ ### Efficient Construction (Bulk Loading)
29
+
30
+ Instead of adding elements one by one, use `fromArray` for maximum performance:
31
+
32
+ ```ts
33
+ import { RecursiveSet, Tuple } from "recursive-set";
34
+
35
+ // Fast: Bulk load sorts and deduplicates in one go
36
+ const states = RecursiveSet.fromArray(["q0", "q1", "q2"]);
37
+
38
+ // Sets of Sets (partitioning)
39
+ const partition = new RecursiveSet<RecursiveSet<string>>();
40
+ partition.add(states); // {{q0, q1, q2}}
41
+
42
+ console.log(partition.toString()); // {{q0, q1, q2}}
43
+ ```
44
+
45
+
46
+ ### Working with Tuples \& Structures
47
+
48
+ ```ts
49
+ // Tuples (ordered pairs / edges) represent structural values
50
+ // They are immutable and cached by default.
51
+ const edge = new Tuple("q0", "q1");
52
+
53
+ const transitions = new RecursiveSet<Tuple<[string, string]>>();
54
+ transitions.add(edge);
55
+ ```
56
+
57
+
58
+ ### Lifecycle (mutable β†’ frozen)
59
+
60
+ Accessing `hashCode` freezes the set to prevent hash corruption.
61
+
62
+ ```ts
63
+ const A = new RecursiveSet(1, 2);
64
+ const B = new RecursiveSet(A); // hashing B may hash A -> A becomes frozen
65
+
66
+ console.log(B.has(A)); // true
67
+
68
+ try {
69
+ A.add(3); // throws after A is frozen
70
+ } catch {
71
+ console.log("A is frozen and cannot be mutated.");
72
+ }
73
+
74
+ // β€œFork” for mutation
75
+ const C = A.mutableCopy();
76
+ C.add(3);
77
+ ```
78
+
79
+
80
+ ## Contracts
81
+
82
+ This library optimizes for raw throughput. Using it correctly requires strict adherence to these rules:
83
+
84
+ 1. **Finite numbers only:** Do not insert `NaN`, `Infinity`, or `-Infinity`. Comparison logic uses fast arithmetic (`a - b`).
85
+ 2. **No mutation:** Do not mutate arrays/tuples/objects after insertion.
86
+ 3. **Type consistency:** Avoid mixing distinct structure types (e.g., `Array` vs `Tuple`) in the same set for the same logical role, as hash-collision edge cases may treat them as equal for performance reasons.
87
+
88
+ Violating the contract can break sorted order invariants, hashing assumptions, and equality semantics (garbage in β†’ garbage out).
89
+
90
+ ### Freeze-on-hash rule
91
+
92
+ - A set is mutable until `hashCode` is accessed.
93
+ - After hashing, mutation methods throw; use `mutableCopy()` to continue editing.
94
+
95
+
96
+ ### Tuple vs Array
97
+
98
+ - `Tuple` is an immutable container: it makes a defensive copy and freezes its internal storage via `Object.freeze()` (shallow immutability).
99
+ - Plain `Array` values are supported as ordered sequences, but they are not frozen by the library.
100
+
101
+ **Recommendation:** For hot loops (like SAT solvers), represent frequently compared β€œsmall composite values” as `Tuple` to benefit from cached hashing and immutability.
102
+
103
+ ## API
104
+
105
+ ### Types
106
+
107
+ ```ts
108
+ export type Primitive = number | string;
109
+ export type Value =
110
+ | Primitive
111
+ | RecursiveSet<any>
112
+ | Tuple<any>
113
+ | ReadonlyArray<Value>;
114
+ ```
115
+
116
+
117
+ ### Construction
118
+
119
+ ```ts
120
+ new RecursiveSet<T>(...elements: T[])
121
+ ```
122
+
123
+ Elements are sorted and deduplicated on construction.
124
+
125
+ ### Bulk loading
126
+
127
+ ```ts
128
+ RecursiveSet.fromArray<T>(elements: T[]): RecursiveSet<T>
129
+ ```
130
+
131
+ Sorts once and deduplicates (typically much faster than many `.add()` calls).
132
+
133
+ ### Unsafe creation
134
+
135
+ ```ts
136
+ RecursiveSet.fromSortedUnsafe<T>(sortedUnique: T[]): RecursiveSet<T>
137
+ ```
138
+
139
+ **Trusted bypass:** Assumes the input array is already strictly sorted (by internal `compare`) and contains no duplicates. Use only when you can guarantee invariants externally.
140
+
141
+ ### Mutation (only while unfrozen)
142
+
143
+ - `add(element: T): this`
144
+ - `remove(element: T): this`
145
+ - `clear(): this`
146
+
147
+
148
+ ### Copying
149
+
150
+ - `mutableCopy(): RecursiveSet<T>` – mutable shallow copy (use after freezing)
151
+ - `clone(): RecursiveSet<T>` – alias for `mutableCopy()`
152
+
153
+
154
+ ### Set operations (return new sets)
155
+
156
+ All operations below return new `RecursiveSet` instances:
157
+
158
+ - `union(other): RecursiveSet<T | U>`
159
+ - `intersection(other): RecursiveSet<T>`
160
+ - `difference(other): RecursiveSet<T>`
161
+ - `symmetricDifference(other): RecursiveSet<T>`
162
+ - `powerset(): RecursiveSet<RecursiveSet<T>>` (guarded; throws if too large)
163
+ - `cartesianProduct<U>(other): RecursiveSet<Tuple<[T, U]>>`
164
+
165
+
166
+ ### Predicates \& properties
167
+
168
+ - `has(element: T): boolean`
169
+ - `equals(other: RecursiveSet<Value>): boolean`
170
+ - `compare(other: RecursiveSet<Value>): number`
171
+ - `isSubset(other): boolean`
172
+ - `isSuperset(other): boolean`
173
+ - `isEmpty(): boolean`
174
+ - `size: number`
175
+ - `hashCode: number` – computes and caches hash; freezes the set
176
+ - `isFrozen: boolean`
177
+
178
+
179
+ ### Ordering rules
180
+
181
+ Internal ordering is deterministic by design:
182
+
183
+ - Type order: `number` < `string` < sequence (`Array`/`Tuple`) < `RecursiveSet`.
184
+ - Sequences compare by length first, then lexicographically element-by-element.
185
+ - Sets compare by cached hash first, then by structural comparison on collision.
186
+
187
+
188
+ ## Credits
189
+
190
+ This library was developed as a student research project under the supervision of **[Karl Stroetmann](https://github.com/karlstroetmann/)**.
191
+
192
+ Special thanks for his architectural guidance towards homogeneous sets and for contributing the "Merge Scan" & "Bulk Loading" optimization concepts that form the high-performance core of this engine.
193
+
194
+ ## Contributing
195
+
196
+ ```bash
197
+ git clone https://github.com/cstrerath/recursive-set.git
198
+ npm install
199
+ npm run build
200
+ npx tsx test/test.ts
201
+ npx tsx test/nqueens.ts
202
+ ```
203
+
204
+
205
+ ## License
206
+
207
+ MIT License Β© 2025 Christian Strerath. See `LICENSE`