forked from baetheus/fun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheq.ts
639 lines (612 loc) · 16.2 KB
/
eq.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
/**
* This file contains all of the tools for creating and
* composing Eqs. Since a Eq encapsulates the concept
* of equality, this file contains a lot of tools for
* comparing objects to see if they are the same, or can
* be treated the same.
*/
import type { In, Kind, Out } from "./kind.ts";
import type { Contravariant } from "./contravariant.ts";
import type { NonEmptyArray } from "./array.ts";
import type { ReadonlyRecord } from "./record.ts";
import type { Literal, Schemable, Spread } from "./schemable.ts";
import { isNil } from "./nilable.ts";
import { memoize } from "./fn.ts";
import { isSubrecord } from "./record.ts";
/**
* A Eq<T> is an algebra with a notion of equality. Specifically,
* a Eq for a type T has an equal method that determines if the
* two objects are the same. Eqs can be combined, like many
* algebraic structures. The combinators for Eq in fun can be found
* in [eq.ts](./eq.ts).
*
* An instance of a Eq must obey the following laws:
*
* 1. Reflexivity: equals(a)(a) === true
* 2. Symmetry: equals(a)(b) === equals(b)(a)
* 3. Transitivity: if equals(a)(b) and equals(b)(c), then equals(a)(c)
*
* The original type came from [static-land](https://github.com/fantasyland/static-land/blob/master/docs/spec.md#Eq)
*
* @since 2.0.0
*/
export interface Eq<T> {
readonly equals: (second: T) => (first: T) => boolean;
}
/**
* Specifies Eq as a Higher Kinded Type, with
* covariant parameter A corresponding to the 0th
* index of any Substitutions.
*
* @since 2.0.0
*/
export interface KindEq extends Kind {
readonly kind: Eq<Out<this, 0>>;
}
/**
* Specifies Eq as a Higher Kinded Type, with
* contravariant parameter D corresponding to the 0th
* index of any Substitutions.
*
* @since 2.0.0
*/
export interface KindContraEq extends Kind {
readonly kind: Eq<In<this, 0>>;
}
/**
* Create a Eq from an uncurried function that checks equality.
*
* @example
* ```ts
* import { fromEquals } from "./eq.ts";
* import { pipe } from "./fn.ts";
*
* const EqNumber = fromEquals<number>(
* (first, second) => first === second
* );
*
* const result = pipe(
* 1,
* EqNumber.equals(1)
* ); // true
* ```
*
* @since 2.0.0
*/
export function fromEquals<A>(
equals: (first: A, second: A) => boolean,
): Eq<A> {
return ({
equals: (second) => (first) => first === second || equals(first, second),
});
}
/**
* Create a Eq that casts the inner type of another Eq to
* Readonly.
*
* @example
* ```ts
* import { readonly, fromEquals } from "./eq.ts";
*
* // This has type Eq<Array<string>>
* const EqMutableArray = fromEquals<Array<string>>(
* (first, second) => first.length === second.length
* && first.every((value, index) => value === second[index])
* );
*
* // This has type Eq<Readonly<Array<string>>>
* const EqReadonlyArray = readonly(EqMutableArray);
* ```
*
* @since 2.0.0
*/
export function readonly<A>(eq: Eq<A>): Eq<Readonly<A>> {
return eq;
}
/**
* A Eq 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 "./eq.ts";
*
* const result1 = unknown.equals(1)("Hello"); // false
* const result2 = unknown.equals(1)(1); // true
* ```
*
* @since 2.0.0
*/
export const unknown: Eq<unknown> = {
equals: (second) => (first) => first === second,
};
/**
* A Eq that compares strings using strict equality.
*
* @example
* ```ts
* import { string } from "./eq.ts";
*
* const result1 = string.equals("World")("Hello"); // false
* const result2 = string.equals("")(""); // true
* ```
*
* @since 2.0.0
*/
export const string: Eq<string> = unknown;
/**
* A Eq that compares number using strict equality.
*
* @example
* ```ts
* import { number } from "./eq.ts";
*
* const result1 = number.equals(1)(2); // false
* const result2 = number.equals(1)(1); // true
* ```
*
* @since 2.0.0
*/
export const number: Eq<number> = unknown;
/**
* A Eq that compares booleans using strict equality.
*
* @example
* ```ts
* import { boolean } from "./eq.ts";
*
* const result1 = boolean.equals(true)(false); // false
* const result2 = boolean.equals(true)(true); // true
* ```
*
* @since 2.0.0
*/
export const boolean: Eq<boolean> = unknown;
/**
* Creates a Eq that compares a union of literals
* using strict equality.
*
* @example
* ```ts
* import { literal } from "./eq.ts";
*
* const { equals } = literal(1, 2, "Three");
*
* const result1 = equals(1)("Three"); // false
* const result2 = equals("Three")("Three"); // true
* ```
*
* @since 2.0.0
*/
export function literal<A extends NonEmptyArray<Literal>>(
..._: A
): Eq<A[number]> {
return unknown;
}
/**
* Creates a derivative Eq that can also compare null
* values in addition to the source eq.
*
* @example
* ```ts
* import { nullable, number } from "./eq.ts";
*
* const { equals } = nullable(number);
*
* const result1 = equals(1)(null); // false
* const result2 = equals(null)(null); // true
* ```
*
* @since 2.0.0
*/
export function nullable<A>(eq: Eq<A>): Eq<A | null> {
return {
equals: (second) => (first) =>
(isNil(first) || isNil(second))
? first === second
: eq.equals(second)(first),
};
}
/**
* Creates a derivative Eq that can also compare undefined
* values in addition to the source eq.
*
* @example
* ```ts
* import { undefinable, number } from "./eq.ts";
*
* const { equals } = undefinable(number);
*
* const result1 = equals(1)(undefined); // false
* const result2 = equals(undefined)(undefined); // true
* ```
*
* @since 2.0.0
*/
export function undefinable<A>(eq: Eq<A>): Eq<A | undefined> {
return {
equals: (second) => (first) =>
(isNil(first) || isNil(second))
? first === second
: eq.equals(second)(first),
};
}
/**
* Creates a Eq that compares readonly records with items
* that have the type compared in the supplied eq.
*
* @example
* ```ts
* import { record, number } from "./eq.ts";
*
* const { equals } = record(number);
*
* const result1 = equals({ one: 1 })({ one: 2 }); // false
* const result2 = equals({ one: 1 })({ one: 1 }); // true
* ```
*
* @since 2.0.0
*/
export function record<A>(eq: Eq<A>): Eq<ReadonlyRecord<A>> {
const isSub = isSubrecord(eq);
return {
equals: (second) => (first) => isSub(second)(first) && isSub(first)(second),
};
}
/**
* Creates a Eq that compares readonly array with items
* that have the type compared in the supplied eq.
*
* @example
* ```ts
* import { array, number } from "./eq.ts";
*
* const { equals } = array(number);
*
* const result1 = equals([1, 2])([1, 2, 3]); // false
* const result2 = equals([1, 2])([1, 2]); // true
* ```
*
* @since 2.0.0
*/
export function array<A>(eq: Eq<A>): Eq<ReadonlyArray<A>> {
return {
equals: (second) => (first) =>
first.length === second.length &&
first.every((value, index) => eq.equals(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 "./eq.ts";
*
* const { equals } = tuple(number, string);
*
* const result1 = equals([1, "Hello"])([1, "Goodbye"]); // false
* const result2 = equals([1, ""])([1, ""]); // true
* ```
*
* @since 2.0.0
*/
// deno-lint-ignore no-explicit-any
export function tuple<T extends ReadonlyArray<Eq<any>>>(
...Eqs: T
): Eq<{ [K in keyof T]: T[K] extends Eq<infer A> ? A : never }> {
return fromEquals((first, second) =>
Eqs.every((E, i) => E.equals(first[i])(second[i]))
);
}
/**
* 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 "./eq.ts";
*
* const { equals } = struct({ name: string, age: number });
*
* const brandon = { name: "Brandon", age: 37 };
* const emily = { name: "Emily", age: 32 };
*
* const result1 = equals(brandon)(emily); // false
* const result2 = equals(brandon)(brandon); // true
* ```
*
* @since 2.0.0
*/
export function struct<A>(
eqs: { readonly [K in keyof A]: Eq<A[K]> },
): Eq<{ readonly [K in keyof A]: A[K] }> {
const _eqs = Object.entries(eqs) as [keyof A, Eq<A[keyof A]>][];
return fromEquals((first, second) =>
_eqs.every(([key, { equals }]) => equals(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 "./eq.ts";
*
* const { equals } = struct({ name: string, age: number });
*
* const brandon = { name: "Brandon", age: 37 };
* const emily = { name: "Emily", age: 32 };
*
* const result1 = equals(brandon)(emily); // false
* const result2 = equals(brandon)(brandon); // true
* ```
*
* @since 2.0.0
*/
export function partial<A>(
Eqs: { readonly [K in keyof A]: Eq<A[K]> },
): Eq<{ readonly [K in keyof A]?: A[K] }> {
const eqs = Object.entries(Eqs) as [keyof A, Eq<A[keyof A]>][];
return fromEquals((first, second) =>
eqs.every(([key, { equals }]) => {
const firstValue = first[key] as A[keyof A] | null | undefined;
const secondValue = second[key] as A[keyof A] | null | undefined;
if (isNil(firstValue) || isNil(secondValue)) {
return firstValue === secondValue;
} else {
return equals(secondValue)(firstValue);
}
})
);
}
/**
* 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 "./eq.ts";
* import { pipe } from "./fn.ts";
*
* const { equals } = pipe(
* struct({ firstName: string }),
* intersect(partial({ lastName: string }))
* );
*
* const batman = { firstName: "Batman" };
* const grace = { firstName: "Grace", lastName: "Hopper" };
*
* const result1 = equals(batman)(grace); // false
* const result2 = equals(grace)(grace); // true
* ```
*
* @since 2.0.0
*/
export function intersect<I>(
second: Eq<I>,
): <A>(first: Eq<A>) => Eq<Spread<A & I>> {
return <A>(first: Eq<A>): Eq<Spread<A & I>> => ({
equals: (snd) => (fst) =>
first.equals(snd as A)(fst as A) && second.equals(snd as I)(fst as I),
});
}
/**
* Create a eq from two other eqs. The resultant eq 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 "./eq.ts";
* import { pipe } from "./fn.ts";
*
* const { equals } = pipe(number, union(string));
*
* const result1 = equals(1)("Hello"); // false
* const result2 = equals(1)(1); // true
* ```
*
* @since 2.0.0
*/
export function union<I>(
ui: Eq<I>,
): <A>(first: Eq<A>) => Eq<A | I> {
return (ua) => ({
equals: (second) => (first) => {
if (first === second) {
return true;
} else {
try {
// deno-lint-ignore no-explicit-any
return ua.equals(second as any)(first as any) ||
// deno-lint-ignore no-explicit-any
ui.equals(second as any)(first as any);
} catch {
return false;
}
}
},
});
}
/**
* 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, Eq } from "./eq.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, child?: Person };
*
* // Annotating the type is required for recursion
* const person: Eq<Person> = lazy('Person', () => pipe(
* struct({ name: string }),
* intersect(partial({ child: person }))
* ));
*
* const icarus = { name: "Icarus" };
* const daedalus = { name: "Daedalus", child: icarus };
*
* const result1 = person.equals(icarus)(daedalus); // false
* const result2 = person.equals(daedalus)(daedalus); // true
* ```
*
* @since 2.0.0
*/
export function lazy<A>(_: string, f: () => Eq<A>): Eq<A> {
const memo = memoize<void, Eq<A>>(f);
return { equals: (second) => (first) => memo().equals(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, io, number } from "./eq.ts";
* import { of as constant } from "./fn.ts";
*
* const { equals } = struct({ asNumber: io(number) });
*
* const one = { asNumber: () => 1 };
* const two = { asNumber: () => 2 };
*
* const result1 = equals(one)(two); // false
* const result2 = equals(one)(one); // true
* ```
*
* @since 2.0.0
*/
export function io<A>(eq: Eq<A>): Eq<() => A> {
return { equals: (second) => (first) => eq.equals(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 "./eq.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.equals(now)(alsoNow); // true
* const result2 = date.equals(now)(later); // false
* ```
*
* @since 2.0.0
*/
export function method<M extends string, A>(
method: M,
eq: Eq<A>,
): Eq<{ readonly [K in M]: () => A }> {
return {
equals: (second) => (first) => eq.equals(second[method]())(first[method]()),
};
}
/**
* Create a Eq<L> using a Eq<D> and a function that takes
* a type L and returns a type D.
*
* @example
* ```ts
* import { contramap, number } from "./eq.ts";
* import { pipe } from "./fn.ts";
*
* const dateToNumber = (d: Date): number => d.valueOf();
* const date = pipe(number, contramap(dateToNumber));
*
* const now = new Date();
* const alsoNow = new Date(Date.now());
* const later = new Date(Date.now() + 60 * 60 * 1000);
*
* const result1 = date.equals(now)(alsoNow); // true
* const result2 = date.equals(now)(later); // false
* ```
*
* Another use for contramap 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 { contramap, string } from "./eq.ts";
* import { pipe } from "./fn.ts";
*
* const lowercase = (s: string) => s.toLowerCase();
* const insensitive = pipe(
* string, // exact string compare
* contramap(lowercase), // makes all strings lowercase
* );
*
* const result1 = insensitive.equals("Hello")("World"); // false
* const result2 = insensitive.equals("hello")("Hello"); // true
* ```
*
* @since 2.0.0
*/
export function contramap<L, D>(
fld: (l: L) => D,
): (eq: Eq<D>) => Eq<L> {
return ({ equals }) => ({
equals: ((second) => (first) => equals(fld(second))(fld(first))),
});
}
/**
* The canonical implementation of Contravariant for Eq. It contains
* the method contramap.
*
* @since 2.0.0
*/
export const ContravariantEq: Contravariant<KindContraEq> = {
contramap,
};
/**
* The canonical implementation of Schemable for a Eq. 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 SchemableEq: Schemable<KindEq> = {
unknown: () => unknown,
string: () => string,
number: () => number,
boolean: () => boolean,
literal,
nullable,
undefinable,
record,
array,
tuple,
struct,
partial,
intersect,
union,
lazy,
};