@mark1russell7/collections 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +78 -2
- package/build/dag/index.d.ts +144 -0
- package/build/dag/index.d.ts.map +1 -0
- package/build/dag/index.js +294 -0
- package/build/dag/index.js.map +1 -0
- package/build/graph/index.d.ts +20 -0
- package/build/graph/index.d.ts.map +1 -0
- package/build/graph/index.js +48 -0
- package/build/graph/index.js.map +1 -0
- package/build/index.d.ts +4967 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7897 -0
- package/build/index.js.map +1 -0
- package/build/testing/index.d.ts +25 -0
- package/build/testing/index.d.ts.map +1 -0
- package/build/testing/index.js +72 -0
- package/build/testing/index.js.map +1 -0
- package/package.json +77 -3
- package/src/async/async-queue.ts +481 -0
- package/src/async/channels.ts +450 -0
- package/src/async/settled.ts +41 -0
- package/src/behaviors/bounded.ts +485 -0
- package/src/behaviors/composite.ts +99 -0
- package/src/behaviors/evented.ts +464 -0
- package/src/behaviors/lru.ts +449 -0
- package/src/behaviors/readonly.ts +236 -0
- package/src/behaviors/safe.ts +358 -0
- package/src/behaviors/synchronized.ts +316 -0
- package/src/behaviors/ttl.ts +464 -0
- package/src/core/effects.ts +327 -0
- package/src/core/events.ts +363 -0
- package/src/core/middleware.ts +413 -0
- package/src/core/policies.ts +316 -0
- package/src/core/traits.ts +164 -0
- package/src/dag/builder.ts +124 -0
- package/src/dag/executor.ts +190 -0
- package/src/dag/index.ts +14 -0
- package/src/dag/traversal.ts +129 -0
- package/src/dag/types.ts +87 -0
- package/src/fx/collectors.ts +500 -0
- package/src/fx/iter.ts +536 -0
- package/src/graph/hub-order.ts +53 -0
- package/src/graph/index.ts +5 -0
- package/src/impl/array-deque.ts +463 -0
- package/src/impl/array-list.ts +490 -0
- package/src/impl/hash-map.ts +623 -0
- package/src/impl/hash-set.ts +342 -0
- package/src/impl/linked-hash-map.ts +572 -0
- package/src/impl/linked-list.ts +610 -0
- package/src/impl/priority-queue.ts +448 -0
- package/src/impl/summary-tree.ts +594 -0
- package/src/impl/tree-map.ts +913 -0
- package/src/impl/tree-set.ts +469 -0
- package/src/index.ts +237 -0
- package/src/interfaces/collection.ts +141 -0
- package/src/interfaces/list.ts +281 -0
- package/src/interfaces/map.ts +405 -0
- package/src/interfaces/queue.ts +353 -0
- package/src/interfaces/set.ts +158 -0
- package/src/order/index.ts +6 -0
- package/src/order/rank.ts +271 -0
- package/src/storage/listeners.ts +72 -0
- package/src/testing/check.ts +81 -0
- package/src/testing/index.ts +7 -0
- package/src/utils/defaults.ts +443 -0
- package/src/utils/factories.ts +357 -0
- package/src/utils/helpers.ts +248 -0
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default implementations of equality, hashing, and comparison functions.
|
|
3
|
+
*
|
|
4
|
+
* This module gives sensible defaults for primitive types and utilities for
|
|
5
|
+
* making custom comparators.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Eq, Hash, Compare } from "../core/traits.js";
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// Default Equality
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Default equality using strict equality (===).
|
|
16
|
+
* Works for primitives and reference equality for objects.
|
|
17
|
+
*/
|
|
18
|
+
export const defaultEq: Eq<any> = (a, b) => a === b;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Structural equality for objects (shallow comparison of properties).
|
|
22
|
+
* This function compares own enumerable properties using ===.
|
|
23
|
+
*/
|
|
24
|
+
export const shallowEq: Eq<any> = (a, b) => {
|
|
25
|
+
if (a === b) return true;
|
|
26
|
+
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
27
|
+
if (a === null || b === null) return false;
|
|
28
|
+
|
|
29
|
+
const keysA = Object.keys(a);
|
|
30
|
+
const keysB = Object.keys(b);
|
|
31
|
+
|
|
32
|
+
if (keysA.length !== keysB.length) return false;
|
|
33
|
+
|
|
34
|
+
for (const key of keysA) {
|
|
35
|
+
if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
|
|
36
|
+
if (a[key] !== b[key]) return false;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return true;
|
|
40
|
+
};
|
|
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
|
+
function bytesOf(value: ArrayBufferLike | DataView): Uint8Array {
|
|
69
|
+
return ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function enumerableKeys(value: object): (string | symbol)[] {
|
|
73
|
+
return Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function equalKeys(a: any, b: any, held: HeldPairs): boolean {
|
|
77
|
+
const keys = enumerableKeys(a);
|
|
78
|
+
if (keys.length !== enumerableKeys(b).length) return false;
|
|
79
|
+
return keys.every((key) => Object.prototype.propertyIsEnumerable.call(b, key) && equalValues(a[key], b[key], held));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The comparison of the entries of two maps, or of the members of two sets. A primitive key finds
|
|
84
|
+
* its partner by `has`. An object key tries each object key of `b` that is not taken yet. The first
|
|
85
|
+
* partner is correct, because the relation is an equivalence.
|
|
86
|
+
*/
|
|
87
|
+
function equalEntries(a: Map<unknown, unknown> | Set<unknown>, b: Map<unknown, unknown> | Set<unknown>, held: HeldPairs): boolean {
|
|
88
|
+
if (a.size !== b.size) return false;
|
|
89
|
+
const valueAt = (key: unknown): unknown => (b instanceof Map ? b.get(key) : key);
|
|
90
|
+
const free = [...b.entries()].filter(([key]) => isObject(key));
|
|
91
|
+
for (const [key, value] of a.entries()) {
|
|
92
|
+
if (!isObject(key)) {
|
|
93
|
+
if (!b.has(key) || !equalValues(value, valueAt(key), held)) return false;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const at = free.findIndex(([otherKey, otherValue]) => {
|
|
97
|
+
const mark = held.log.length;
|
|
98
|
+
if (equalValues(key, otherKey, held) && equalValues(value, otherValue, held)) return true;
|
|
99
|
+
releasePairs(held, mark);
|
|
100
|
+
return false;
|
|
101
|
+
});
|
|
102
|
+
if (at < 0) return false;
|
|
103
|
+
free.splice(at, 1);
|
|
104
|
+
}
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The comparison of two objects with the same prototype. */
|
|
109
|
+
function equalObjects(a: any, b: any, held: HeldPairs): boolean {
|
|
110
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
111
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
|
112
|
+
for (let i = 0; i < a.length; i++) {
|
|
113
|
+
if (!equalValues(a[i], b[i], held)) return false;
|
|
114
|
+
}
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
if (a instanceof DataView || a instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && a instanceof SharedArrayBuffer)) {
|
|
118
|
+
return equalElements(bytesOf(a), bytesOf(b));
|
|
119
|
+
}
|
|
120
|
+
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;
|
|
122
|
+
if (a instanceof Date && !sameValueZero(a.getTime(), b.getTime())) return false;
|
|
123
|
+
if (a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags)) return false;
|
|
124
|
+
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;
|
|
127
|
+
if ((a instanceof Map || a instanceof Set) && !equalEntries(a, b, held)) return false;
|
|
128
|
+
return equalKeys(a, b, held);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The comparison of two values. A pair stays held after it passes, so a shared or cyclic part
|
|
133
|
+
* costs one visit. A failure ends the whole comparison, or the try in `equalEntries`, which
|
|
134
|
+
* releases its pairs.
|
|
135
|
+
*/
|
|
136
|
+
function equalValues(a: unknown, b: unknown, held: HeldPairs): boolean {
|
|
137
|
+
if (sameValueZero(a, b)) return true;
|
|
138
|
+
if (!isObject(a) || !isObject(b)) return false;
|
|
139
|
+
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
|
|
140
|
+
let partners = held.partners.get(a);
|
|
141
|
+
if (partners?.has(b)) return true;
|
|
142
|
+
if (partners === undefined) {
|
|
143
|
+
partners = new Set();
|
|
144
|
+
held.partners.set(a, partners);
|
|
145
|
+
}
|
|
146
|
+
partners.add(b);
|
|
147
|
+
held.log.push([a, b]);
|
|
148
|
+
return equalObjects(a, b, held);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Deep structural equality. This relation is an equivalence: it is reflexive, symmetric and
|
|
153
|
+
* transitive, for each value.
|
|
154
|
+
*
|
|
155
|
+
* - Primitives compare by SameValueZero: NaN equals NaN, and 0 equals -0.
|
|
156
|
+
* - Two objects must have the same prototype. So `{}` differs from `Object.create(null)`, from an
|
|
157
|
+
* instance of a class with the same keys, and from an object of another realm.
|
|
158
|
+
* - Arrays compare by length and by index. A hole equals `undefined`.
|
|
159
|
+
* - Typed arrays compare by element. `ArrayBuffer`, `SharedArrayBuffer` and `DataView` compare by byte.
|
|
160
|
+
* - `Date` compares by time, `RegExp` by source and flags, and `Error` by name, message and cause.
|
|
161
|
+
* - A boxed primitive compares by its value. `Map` and `Set` compare by entries, in any order. An object key
|
|
162
|
+
* matches a deep-equal key.
|
|
163
|
+
* - Each other object compares by its own enumerable keys, strings and symbols, in any order. The objects above do too,
|
|
164
|
+
* except arrays and binary data.
|
|
165
|
+
* - Functions, `Promise`, `WeakMap`, `WeakSet` and `WeakRef` compare by identity.
|
|
166
|
+
* - Cycles are safe: two cyclic values are equal when they unfold to the same infinite tree.
|
|
167
|
+
*
|
|
168
|
+
* The recursion follows the depth of the data, so a very deep value can exhaust the stack.
|
|
169
|
+
*/
|
|
170
|
+
export const deepEq: Eq<any> = (a, b): boolean => equalValues(a, b, { partners: new Map(), log: [] });
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Equality by comparing a specific property.
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* const userEq = eqBy<User, 'id'>('id')
|
|
177
|
+
* // or with accessor function:
|
|
178
|
+
* const userEq = eqBy<User>((u) => u.id)
|
|
179
|
+
*/
|
|
180
|
+
export const eqBy = <T, K extends keyof T = keyof T>(
|
|
181
|
+
keyOrFn: K | ((value: T) => any)
|
|
182
|
+
): Eq<T> => {
|
|
183
|
+
const accessor = typeof keyOrFn === "function" ? keyOrFn : (v: T) => v[keyOrFn];
|
|
184
|
+
return (a, b) => accessor(a) === accessor(b);
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// ============================================================================
|
|
188
|
+
// Default Hashing
|
|
189
|
+
// ============================================================================
|
|
190
|
+
|
|
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 => {
|
|
196
|
+
if (value === null) return 0;
|
|
197
|
+
if (value === undefined) return 1;
|
|
198
|
+
|
|
199
|
+
const type = typeof value;
|
|
200
|
+
|
|
201
|
+
switch (type) {
|
|
202
|
+
case "boolean":
|
|
203
|
+
return value ? 1 : 0;
|
|
204
|
+
case "number":
|
|
205
|
+
return hashNumber(value);
|
|
206
|
+
case "string":
|
|
207
|
+
return hashString(value);
|
|
208
|
+
case "symbol":
|
|
209
|
+
return hashString(value.toString());
|
|
210
|
+
case "bigint":
|
|
211
|
+
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
|
+
default:
|
|
222
|
+
return 2;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Hash function for strings using djb2 algorithm.
|
|
228
|
+
*/
|
|
229
|
+
export const hashString = (str: string): number => {
|
|
230
|
+
let hash = 5381;
|
|
231
|
+
for (let i = 0; i < str.length; i++) {
|
|
232
|
+
hash = ((hash << 5) + hash) + str.charCodeAt(i); // hash * 33 + c
|
|
233
|
+
hash = hash & hash; // Convert to 32-bit integer
|
|
234
|
+
}
|
|
235
|
+
return hash >>> 0; // Convert to unsigned
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Hash function for numbers.
|
|
240
|
+
*/
|
|
241
|
+
export const hashNumber = (num: number): number => {
|
|
242
|
+
if (Number.isNaN(num)) return 0;
|
|
243
|
+
if (!Number.isFinite(num)) return num > 0 ? 1 : -1;
|
|
244
|
+
|
|
245
|
+
// For integers, use the number itself
|
|
246
|
+
if (Number.isInteger(num)) {
|
|
247
|
+
return num | 0; // Convert to 32-bit int
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// For floats, hash the string representation
|
|
251
|
+
return hashString(num.toString());
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Combine multiple hash values.
|
|
256
|
+
* Useful for hashing objects with multiple fields.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* const pointHash: Hash<Point> = (p) =>
|
|
260
|
+
* combineHashes(hashNumber(p.x), hashNumber(p.y))
|
|
261
|
+
*/
|
|
262
|
+
export const combineHashes = (...hashes: number[]): number => {
|
|
263
|
+
let combined = 0;
|
|
264
|
+
for (const hash of hashes) {
|
|
265
|
+
combined = ((combined << 5) - combined) + hash;
|
|
266
|
+
combined = combined & combined; // Convert to 32-bit int
|
|
267
|
+
}
|
|
268
|
+
return combined >>> 0; // Convert to unsigned
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Make a hash function that hashes by a specific property.
|
|
273
|
+
*
|
|
274
|
+
* @example
|
|
275
|
+
* const userHash = hashBy<User>((u) => u.id)
|
|
276
|
+
*/
|
|
277
|
+
export const hashBy = <T>(accessor: (value: T) => any): Hash<T> => {
|
|
278
|
+
return (value) => defaultHash(accessor(value));
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// ============================================================================
|
|
282
|
+
// Default Comparison
|
|
283
|
+
// ============================================================================
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Natural ordering comparison for primitives.
|
|
287
|
+
* Numbers, strings, booleans, dates are compared naturally.
|
|
288
|
+
*/
|
|
289
|
+
export const defaultCompare: Compare<any> = (a, b) => {
|
|
290
|
+
if (a === b) return 0;
|
|
291
|
+
if (a === null || a === undefined) return -1;
|
|
292
|
+
if (b === null || b === undefined) return 1;
|
|
293
|
+
|
|
294
|
+
// Handle dates
|
|
295
|
+
if (a instanceof Date && b instanceof Date) {
|
|
296
|
+
return a.getTime() - b.getTime();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Handle numbers
|
|
300
|
+
if (typeof a === "number" && typeof b === "number") {
|
|
301
|
+
if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : -1;
|
|
302
|
+
if (Number.isNaN(b)) return 1;
|
|
303
|
+
return a - b;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Handle strings
|
|
307
|
+
if (typeof a === "string" && typeof b === "string") {
|
|
308
|
+
return a.localeCompare(b);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Handle booleans
|
|
312
|
+
if (typeof a === "boolean" && typeof b === "boolean") {
|
|
313
|
+
return a === b ? 0 : a ? 1 : -1;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Fallback: convert to string and compare
|
|
317
|
+
return String(a).localeCompare(String(b));
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Numeric comparison (for numbers).
|
|
322
|
+
*/
|
|
323
|
+
export const numberCompare: Compare<number> = (a, b) => {
|
|
324
|
+
if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : -1;
|
|
325
|
+
if (Number.isNaN(b)) return 1;
|
|
326
|
+
return a - b;
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* String comparison using locale-aware sorting.
|
|
331
|
+
*/
|
|
332
|
+
export const stringCompare: Compare<string> = (a, b) => a.localeCompare(b);
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Case-insensitive string comparison.
|
|
336
|
+
*/
|
|
337
|
+
export const stringCompareIgnoreCase: Compare<string> = (a, b) =>
|
|
338
|
+
a.toLowerCase().localeCompare(b.toLowerCase());
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Date comparison.
|
|
342
|
+
*/
|
|
343
|
+
export const dateCompare: Compare<Date> = (a, b) =>
|
|
344
|
+
a.getTime() - b.getTime();
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Boolean comparison (false < true).
|
|
348
|
+
*/
|
|
349
|
+
export const booleanCompare: Compare<boolean> = (a, b) =>
|
|
350
|
+
a === b ? 0 : a ? 1 : -1;
|
|
351
|
+
|
|
352
|
+
// ============================================================================
|
|
353
|
+
// Comparator Combinators
|
|
354
|
+
// ============================================================================
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* This function reverses a comparator.
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
* const descending = reversed(numberCompare)
|
|
361
|
+
*/
|
|
362
|
+
export const reversed = <T>(compare: Compare<T>): Compare<T> =>
|
|
363
|
+
(a, b) => compare(b, a);
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* This function makes a comparator that compares by a specific property or function.
|
|
367
|
+
*
|
|
368
|
+
* @example
|
|
369
|
+
* const byAge = comparing<Person>((p) => p.age)
|
|
370
|
+
* const byName = comparing<Person, 'name'>('name')
|
|
371
|
+
*/
|
|
372
|
+
export const comparing = <T, K extends keyof T = keyof T>(
|
|
373
|
+
keyOrFn: K | ((value: T) => any),
|
|
374
|
+
compare: Compare<any> = defaultCompare
|
|
375
|
+
): Compare<T> => {
|
|
376
|
+
const accessor = typeof keyOrFn === "function" ? keyOrFn : (v: T) => v[keyOrFn];
|
|
377
|
+
return (a, b) => compare(accessor(a), accessor(b));
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Chains comparators. If the first comparator gives 0 (equal),
|
|
382
|
+
* tries the next comparator, and so on.
|
|
383
|
+
*
|
|
384
|
+
* @example
|
|
385
|
+
* const userCompare = thenComparing(
|
|
386
|
+
* comparing<User>('lastName'),
|
|
387
|
+
* comparing<User>('firstName'),
|
|
388
|
+
* comparing<User>('age')
|
|
389
|
+
* )
|
|
390
|
+
*/
|
|
391
|
+
export const thenComparing = <T>(...comparators: Compare<T>[]): Compare<T> => {
|
|
392
|
+
return (a, b) => {
|
|
393
|
+
for (const compare of comparators) {
|
|
394
|
+
const result = compare(a, b);
|
|
395
|
+
if (result !== 0) return result;
|
|
396
|
+
}
|
|
397
|
+
return 0;
|
|
398
|
+
};
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* This function makes a comparator that treats null/undefined as less than all other values.
|
|
403
|
+
*
|
|
404
|
+
* @example
|
|
405
|
+
* const compare = nullsFirst(numberCompare)
|
|
406
|
+
*/
|
|
407
|
+
export const nullsFirst = <T>(compare: Compare<T>): Compare<T | null | undefined> => {
|
|
408
|
+
return (a, b) => {
|
|
409
|
+
if (a == null && b == null) return 0;
|
|
410
|
+
if (a == null) return -1;
|
|
411
|
+
if (b == null) return 1;
|
|
412
|
+
return compare(a, b);
|
|
413
|
+
};
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* This function makes a comparator that treats null/undefined as greater than all other values.
|
|
418
|
+
*
|
|
419
|
+
* @example
|
|
420
|
+
* const compare = nullsLast(numberCompare)
|
|
421
|
+
*/
|
|
422
|
+
export const nullsLast = <T>(compare: Compare<T>): Compare<T | null | undefined> => {
|
|
423
|
+
return (a, b) => {
|
|
424
|
+
if (a == null && b == null) return 0;
|
|
425
|
+
if (a == null) return 1;
|
|
426
|
+
if (b == null) return -1;
|
|
427
|
+
return compare(a, b);
|
|
428
|
+
};
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* This function makes a comparator from a key extraction function.
|
|
433
|
+
* Elements are compared by their extracted keys.
|
|
434
|
+
*
|
|
435
|
+
* @example
|
|
436
|
+
* const byLength = comparingKey<string>((s) => s.length)
|
|
437
|
+
*/
|
|
438
|
+
export const comparingKey = <T, K>(
|
|
439
|
+
keyExtractor: (value: T) => K,
|
|
440
|
+
keyCompare: Compare<K> = defaultCompare
|
|
441
|
+
): Compare<T> => {
|
|
442
|
+
return (a, b) => keyCompare(keyExtractor(a), keyExtractor(b));
|
|
443
|
+
};
|