-
Notifications
You must be signed in to change notification settings - Fork 6
/
comparable.ts
649 lines (620 loc) · 17.2 KB
/
comparable.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/**
* Comparable is a structure that has an idea of comparability. Comparability
* means that two of the same type of object can be compared such that the
* condition of comparison can be true or false. The canonical comparison is
* equality.
*
* @module Comparable
* @since 2.0.0
*/
import type { Hold, In, Kind, Out, Spread } from "./kind.ts";
import type { NonEmptyArray } from "./array.ts";
import type { ReadonlyRecord } from "./record.ts";
import type { Literal, Schemable } from "./schemable.ts";
import { handleThrow, identity, memoize, uncurry2 } from "./fn.ts";
import { isSubrecord } from "./record.ts";
/**
* The compare function in a Comparable.
*
* @since 2.0.0
*/
export type Compare<A> = (second: A) => (first: A) => boolean;
/**
* @since 2.0.0
*/
export type TypeOf<U> = U extends Comparable<infer A> ? A : never;
/**
* A Comparable<T> is an algebra with a notion of equality. Specifically,
* a Comparable for a type T has an equal method that determines if the
* two objects are the same. Comparables can be combined, like many
* algebraic structures. The combinators for Comparable in fun can be found
* in [comparable.ts](./comparable.ts).
*
* An instance of a Comparable must obey the following laws:
*
* 1. Reflexivity: compare(a, a) === true
* 2. Symmetry: compare(a, b) === compare(b, a)
* 3. Transitivity: if compare(a, b) and compare(b, c), then compare(a, c)
*
* @since 2.0.0
*/
export interface Comparable<A> extends Hold<A> {
readonly compare: Compare<A>;
}
/**
* Specifies Comparable as a Higher Kinded Type, with
* covariant parameter A corresponding to the 0th
* index of any Substitutions.
*
* @since 2.0.0
*/
export interface KindComparable extends Kind {
readonly kind: Comparable<Out<this, 0>>;
}
/**
* Specifies Comparable as a Higher Kinded Type, with
* contravariant parameter D corresponding to the 0th
* index of any Substitutions.
*
* @since 2.0.0
*/
export interface KindContraComparable extends Kind {
readonly kind: Comparable<In<this, 0>>;
}
/**
* Create a Comparable from a Compare function.
*
* @example
* ```ts
* import { fromCompare } from "./comparable.ts";
* import { pipe } from "./fn.ts";
*
* const { compare } = fromCompare<number>(
* (second) => (first) => first === second
* );
*
* const result = compare(1)(1); // true
* ```
*
* @since 2.0.0
*/
export function fromCompare<A>(
compare: Compare<A> = (second) => (first) => first === second,
): Comparable<A> {
return { compare };
}
/**
* A single instance of Camparable that uses strict equality for comparison.
*/
// deno-lint-ignore no-explicit-any
const STRICT_EQUALITY: Comparable<any> = fromCompare();
/**
* Create a Comparable that casts the inner type of another Comparable to
* Readonly.
*
* @example
* ```ts
* import { readonly, fromCompare } from "./comparable.ts";
*
* // This has type Comparable<Array<string>>
* const ComparableMutableArray = fromCompare<Array<string>>(
* (second) => (first) => first.length === second.length
* && first.every((value, index) => value === second[index])
* );
*
* // This has type Comparable<Readonly<Array<string>>>
* const ComparableReadonlyArray = readonly(ComparableMutableArray);
* ```
*
* @since 2.0.0
*/
export function readonly<A>(
comparable: Comparable<A>,
): Comparable<Readonly<A>> {
return comparable;
}
/**
* A Comparable that can compare any unknown values (and thus can
* compare any values). Underneath it uses strict equality
* for the comparison.
*
* @example
* ```ts
* import { unknown } from "./comparable.ts";
*
* const result1 = unknown.compare(1)("Hello"); // false
* const result2 = unknown.compare(1)(1); // true
* ```
*
* @since 2.0.0
*/
export const unknown: Comparable<unknown> = STRICT_EQUALITY;
/**
* A Comparable that compares strings using strict equality.
*
* @example
* ```ts
* import { string } from "./comparable.ts";
*
* const result1 = string.compare("World")("Hello"); // false
* const result2 = string.compare("")(""); // true
* ```
*
* @since 2.0.0
*/
export const string: Comparable<string> = STRICT_EQUALITY;
/**
* A Comparable that compares number using strict equality.
*
* @example
* ```ts
* import { number } from "./comparable.ts";
*
* const result1 = number.compare(1)(2); // false
* const result2 = number.compare(1)(1); // true
* ```
*
* @since 2.0.0
*/
export const number: Comparable<number> = STRICT_EQUALITY;
/**
* A Comparable that compares booleans using strict equality.
*
* @example
* ```ts
* import { boolean } from "./comparable.ts";
*
* const result1 = boolean.compare(true)(false); // false
* const result2 = boolean.compare(true)(true); // true
* ```
*
* @since 2.0.0
*/
export const boolean: Comparable<boolean> = STRICT_EQUALITY;
/**
* Creates a Comparable that compares a union of literals
* using strict equality.
*
* @example
* ```ts
* import { literal } from "./comparable.ts";
*
* const { compare } = literal(1, 2, "Three");
*
* const result1 = compare(1)("Three"); // false
* const result2 = compare("Three")("Three"); // true
* ```
*
* @since 2.0.0
*/
export function literal<A extends NonEmptyArray<Literal>>(
..._: A
): Comparable<A[number]> {
return STRICT_EQUALITY;
}
/**
* Creates a derivative Comparable that can also compare null
* values in addition to the source eq.
*
* @example
* ```ts
* import { nullable, number } from "./comparable.ts";
*
* const { compare } = nullable(number);
*
* const result1 = compare(1)(null); // false
* const result2 = compare(null)(null); // true
* ```
*
* @since 2.0.0
*/
export function nullable<A>({ compare }: Comparable<A>): Comparable<A | null> {
return fromCompare((second) => (first) =>
first === null || second === null
? first === second
: compare(second)(first)
);
}
/**
* Creates a derivative Comparable that can also compare undefined
* values in addition to the source eq.
*
* @example
* ```ts
* import { undefinable, number } from "./comparable.ts";
*
* const { compare } = undefinable(number);
*
* const result1 = compare(1)(undefined); // false
* const result2 = compare(undefined)(undefined); // true
* ```
*
* @since 2.0.0
*/
export function undefinable<A>(
{ compare }: Comparable<A>,
): Comparable<A | undefined> {
return fromCompare((second) => (first) =>
first === undefined || second === undefined
? first === second
: compare(second)(first)
);
}
/**
* Creates a Comparable that compares readonly records with items
* that have the type compared in the supplied eq.
*
* @example
* ```ts
* import { record, number } from "./comparable.ts";
*
* const { compare } = record(number);
*
* const result1 = compare({ one: 1 })({ one: 2 }); // false
* const result2 = compare({ one: 1 })({ one: 1 }); // true
* ```
*
* @since 2.0.0
*/
export function record<A>(eq: Comparable<A>): Comparable<ReadonlyRecord<A>> {
const isSub = isSubrecord(eq);
return fromCompare((second) => (first) =>
isSub(second)(first) && isSub(first)(second)
);
}
/**
* Creates a Comparable that compares readonly array with items
* that have the type compared in the supplied eq.
*
* @example
* ```ts
* import { array, number } from "./comparable.ts";
*
* const { compare } = array(number);
*
* const result1 = compare([1, 2])([1, 2, 3]); // false
* const result2 = compare([1, 2])([1, 2]); // true
* ```
*
* @since 2.0.0
*/
export function array<A>(
{ compare }: Comparable<A>,
): Comparable<ReadonlyArray<A>> {
return fromCompare((second) => (first) =>
Array.isArray(first) && Array.isArray(second) &&
first.length === second.length &&
first.every((value, index) => compare(second[index])(value))
);
}
/**
* Creates a eq that compares, index for index, tuples according
* to the order and eqs passed into tuple.
*
* @example
* ```ts
* import { tuple, number, string } from "./comparable.ts";
*
* const { compare } = tuple(number, string);
*
* const result1 = compare([1, "Hello"])([1, "Goodbye"]); // false
* const result2 = compare([1, ""])([1, ""]); // true
* ```
*
* @since 2.0.0
*/
// deno-lint-ignore no-explicit-any
export function tuple<T extends ReadonlyArray<Comparable<any>>>(
...comparables: T
): Comparable<
{ [K in keyof T]: T[K] extends Comparable<infer A> ? A : never }
> {
return fromCompare((second) => (first) =>
Array.isArray(first) && Array.isArray(second) &&
first.length === second.length &&
comparables.every(({ compare }, index) =>
compare(second[index])(first[index])
)
);
}
/**
* Create a eq that compares, key for key, structs according
* to the structure of the eqs passed into struct.
*
* @example
* ```ts
* import { struct, number, string } from "./comparable.ts";
*
* const { compare } = struct({ name: string, age: number });
*
* const brandon = { name: "Brandon", age: 37 };
* const emily = { name: "Emily", age: 32 };
*
* const result1 = compare(brandon)(emily); // false
* const result2 = compare(brandon)(brandon); // true
* ```
*
* @since 2.0.0
*/
export function struct<A>(
comparables: { readonly [K in keyof A]: Comparable<A[K]> },
): Comparable<{ readonly [K in keyof A]: A[K] }> {
const _comparables = Object.entries(comparables) as [
keyof A,
Comparable<A[keyof A]>,
][];
return fromCompare((second) => (first) =>
_comparables.every(([key, { compare }]) => compare(second[key])(first[key]))
);
}
/**
* Create a eq that compares, key for key, structs according
* to the structure of the eqs passed into struct. It allows
* the values in the struct to be optional or null.
*
* @example
* ```ts
* import { struct, number, string } from "./comparable.ts";
*
* const { compare } = struct({ name: string, age: number });
*
* const brandon = { name: "Brandon", age: 37 };
* const emily = { name: "Emily", age: 32 };
*
* const result1 = compare(brandon)(emily); // false
* const result2 = compare(brandon)(brandon); // true
* ```
*
* @since 2.0.0
*/
export function partial<A>(
comparables: { readonly [K in keyof A]: Comparable<A[K]> },
): Comparable<{ readonly [K in keyof A]?: A[K] }> {
const _comparables = Object.entries(comparables) as [
keyof A,
Comparable<A[keyof A]>,
][];
return fromCompare((second) => (first) =>
_comparables.every(([key, { compare }]) => {
if (key in first && key in second) {
return compare(second[key] as A[keyof A])(first[key] as A[keyof A]);
}
return first[key] === second[key];
})
);
}
/**
* Create a eq from two other eqs. The resultant eq checks
* that any two values are equal according to both supplied eqs.
*
* @example
* ```ts
* import { intersect, struct, partial, string } from "./comparable.ts";
* import { pipe } from "./fn.ts";
*
* const { compare } = pipe(
* struct({ firstName: string }),
* intersect(partial({ lastName: string }))
* );
*
* const batman = { firstName: "Batman" };
* const grace = { firstName: "Grace", lastName: "Hopper" };
*
* const result1 = compare(batman)(grace); // false
* const result2 = compare(grace)(grace); // true
* ```
*
* @since 2.0.0
*/
export function intersect<I>(
second: Comparable<I>,
): <A>(first: Comparable<A>) => Comparable<Spread<A & I>> {
return <A>(first: Comparable<A>): Comparable<Spread<A & I>> =>
fromCompare((snd: A & I) => (fst: A & I) =>
first.compare(snd)(fst) && second.compare(snd)(fst)
) as Comparable<Spread<A & I>>;
}
/**
* Create a Comparable from two other Comparables. The resultant Comparable checks
* that any two values are equal according to at least one of the supplied
* eqs.
*
* It should be noted that we cannot differentiate the eq used to
* compare two disparate types like number and number[]. Thus, internally
* union must type cast to any and treat thrown errors as a false
* equivalence.
*
* @example
* ```ts
* import { union, number, string } from "./comparable.ts";
* import { pipe } from "./fn.ts";
*
* const { compare } = pipe(number, union(string));
*
* const result1 = compare(1)("Hello"); // false
* const result2 = compare(1)(1); // true
* ```
*
* @since 2.0.0
*/
export function union<I>(
second: Comparable<I>,
): <A>(first: Comparable<A>) => Comparable<A | I> {
return <A>(first: Comparable<A>) => {
const _first = handleThrow(
uncurry2(first.compare),
identity,
() => false,
);
const _second = handleThrow(
uncurry2(second.compare),
identity,
() => false,
);
// deno-lint-ignore no-explicit-any
return fromCompare((snd: any) => (fst: any) =>
_first(fst, snd) || _second(fst, snd)
);
};
}
/**
* Create a eq that evaluates lazily. This is useful for equality
* of recursive types (either mutual or otherwise).
*
* @example
* ```ts
* import { lazy, intersect, struct, partial, string, Comparable } from "./comparable.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, child?: Person };
*
* // Annotating the type is required for recursion
* const person: Comparable<Person> = lazy('Person', () => pipe(
* struct({ name: string }),
* intersect(partial({ child: person }))
* ));
*
* const icarus = { name: "Icarus" };
* const daedalus = { name: "Daedalus", child: icarus };
*
* const result1 = person.compare(icarus)(daedalus); // false
* const result2 = person.compare(daedalus)(daedalus); // true
* ```
*
* @since 2.0.0
*/
export function lazy<A>(_: string, f: () => Comparable<A>): Comparable<A> {
const memo = memoize<void, Comparable<A>>(f);
return fromCompare((second) => (first) => memo().compare(second)(first));
}
/**
* Create a eq that tests the output of a thunk (IO). This assumes that
* the output of the thunk is always the same, which for true IO is not
* the case. This assumes that the context for the function is undefined,
* which means that it doesn't rely on "this" to execute.
*
* @example
* ```ts
* import { struct, thunk, number } from "./comparable.ts";
*
* const { compare } = struct({ asNumber: thunk(number) });
*
* const one = { asNumber: () => 1 };
* const two = { asNumber: () => 2 };
*
* const result1 = compare(one)(two); // false
* const result2 = compare(one)(one); // true
* ```
*
* @since 2.0.0
*/
export function thunk<A>({ compare }: Comparable<A>): Comparable<() => A> {
return fromCompare((second) => (first) => compare(second())(first()));
}
/**
* Create a eq from a method on a class or prototypical object. This
* exists because many objects in javascript do now allow you to pass an
* object method around on its own without its parent object. For example,
* if you pass Date.valueOf (type () => number) into another function and
* call it, the call will fail because valueOf does not carry the reference
* of its parent object around.
*
* @example
* ```ts
* import { method, number } from "./comparable.ts";
*
* // This eq will work for date, but also for any objects that have
* // a valueOf method that returns a number.
* const date = method("valueOf", number);
*
* const now = new Date();
* const alsoNow = new Date(Date.now());
* const later = new Date(Date.now() + 60 * 60 * 1000);
*
* const result1 = date.compare(now)(alsoNow); // true
* const result2 = date.compare(now)(later); // false
* ```
*
* @since 2.0.0
*/
export function method<M extends string, A>(
method: M,
{ compare }: Comparable<A>,
): Comparable<{ readonly [K in M]: () => A }> {
return fromCompare((second) => (first) =>
compare(second[method]())(first[method]())
);
}
/**
* Create a Comparable<L> using a Comparable<D> and a function that takes
* a type L and returns a type D.
*
* @example
* ```ts
* import { premap, number } from "./comparable.ts";
* import { pipe } from "./fn.ts";
*
* const dateToNumber = (d: Date): number => d.valueOf();
* const date = pipe(number, premap(dateToNumber));
*
* const now = new Date();
* const alsoNow = new Date(Date.now());
* const later = new Date(Date.now() + 60 * 60 * 1000);
*
* const result1 = date.compare(now)(alsoNow); // true
* const result2 = date.compare(now)(later); // false
* ```
*
* Another use for premap with eq is to check for
* equality after normalizing data. In the following we
* can compare strings ignoring case by normalizing to
* lowercase strings.
*
* @example
* ```ts
* import { premap, string } from "./comparable.ts";
* import { pipe } from "./fn.ts";
*
* const lowercase = (s: string) => s.toLowerCase();
* const insensitive = pipe(
* string, // exact string compare
* premap(lowercase), // makes all strings lowercase
* );
*
* const result1 = insensitive.compare("Hello")("World"); // false
* const result2 = insensitive.compare("hello")("Hello"); // true
* ```
*
* @since 2.0.0
*/
export function premap<L, D>(
fld: (l: L) => D,
): (eq: Comparable<D>) => Comparable<L> {
return ({ compare }) =>
fromCompare((second) => (first) => compare(fld(second))(fld(first)));
}
/**
* The canonical implementation of Schemable for a Comparable. It contains
* the methods unknown, string, number, boolean, literal, nullable,
* undefinable, record, array, tuple, struct, partial, intersect,
* union, and lazy.
*
* @since 2.0.0
*/
export const SchemableComparable: Schemable<KindComparable> = {
unknown: () => unknown,
string: () => string,
number: () => number,
boolean: () => boolean,
literal,
nullable,
undefinable,
record,
array,
tuple,
struct,
partial,
intersect,
union,
lazy,
};