-
Notifications
You must be signed in to change notification settings - Fork 15
/
test.js
4574 lines (4306 loc) · 164 KB
/
test.js
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const Test = require('thunk-test')
const assert = require('assert')
const stream = require('stream')
const path = require('path')
const fs = require('fs')
const { Readable, Writable } = require('stream')
const util = require('util')
const Transducer = require('./Transducer')
const rubico = require('./rubico')
const isDeepEqual = require('./x/isDeepEqual')
const mapFrom = require('./_internal/mapFrom')
const sha256 = require('./_internal/sha256')
const {
pipe, compose, tap,
tryCatch, switchCase,
all, assign, get, set, pick, omit,
map, filter, flatMap, forEach, reduce, transform,
some, every, and, or, not,
eq, gt, lt, gte, lte,
thunkify, always,
curry, __,
} = rubico
const objectProto = Object.prototype
const symbolAsyncIterator = Symbol.asyncIterator
const nativeObjectToString = objectProto.toString
const objectToString = x => nativeObjectToString.call(x)
const ase = assert.strictEqual
const ade = assert.deepEqual
const aok = assert.ok
const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms) })
const hi = x => `${x}hi`
const ho = x => `${x}ho`
const isOdd = x => (x % 2 === 1)
const square = x => x ** 2
const arrayOf = (getter, length) => Array.from(
{ length },
typeof getter === 'function' ? getter : () => getter,
)
const async = func => async function asyncFunc(...args) {
return func(...args)
}
const delay = (func, ms) => async function delayed(...args) {
await new Promise(resolve => setTimeout(resolve, ms))
return func(...args)
}
const asyncIsEven = x => new Promise(resolve => {
setImmediate(() => resolve(x % 2 === 0))
})
const asyncHey = x => new Promise(resolve => {
setImmediate(() => resolve(`${x}hey`))
})
const asyncMult = (y, xi) => new Promise(resolve => {
setImmediate(() => resolve(y * xi))
})
const constructReadStream = iterable => {
const y = new stream.Readable({ objectMode: true })
y._read = () => {}
for (const x of iterable) y.push(x)
y.push(null)
return y
}
const readStreamToArray = readStream => new Promise((resolve, reject) => {
let result = ''
readStream.on('data', chunk => (result += chunk))
readStream.on('end', () => resolve(result))
readStream.on('error', reject)
})
const consumeReadStreamPush = s => new Promise((resolve, reject) => {
let y = ''
s.on('data', chunk => { y += chunk })
s.on('end', () => resolve(y))
s.on('error', err => reject(err))
})
const consumeReadStreamPull = s => new Promise((resolve, reject) => {
let y = ''
s.on('readable', () => {
let chunk = s.read()
while (chunk != null) {
y += `${chunk}`
chunk = s.read()
}
})
s.on('end', () => resolve(y))
s.on('error', err => reject(err))
})
const makeNumbers = function*() {
for (let i = 0; i < 5; i++) yield i + 1
}
const makeAsyncNumbers = async function*() {
for (let i = 0; i < 5; i++) yield i + 1
}
const iteratorToArray = x => {
let isAsync = false
const y = []
for (const xi of x) {
if (xi instanceof Promise) isAsync = true
y.push(xi)
}
return isAsync ? Promise.all(y) : y
}
const asyncIteratorToArray = async x => {
const y = []
for await (const xi of x) y.push(xi)
return y
}
const typedArrayConstructors = [
Uint8ClampedArray,
Uint8Array, Int8Array,
Uint16Array, Int16Array,
Uint32Array, Int32Array,
Float32Array, Float64Array,
BigUint64Array, BigInt64Array,
]
const numberTypedArrayConstructors = [
Uint8ClampedArray,
Uint8Array, Int8Array,
Uint16Array, Int16Array,
Uint32Array, Int32Array,
Float32Array, Float64Array,
]
const bigIntTypedArrayConstructors = [
BigUint64Array, BigInt64Array,
]
const AssertionError = function (message) {
this.message = message
this.stack = new Error().stack
}
/* Assertion.test(reduce(add, 0), {
args: { 0: [1, 2, 3, 4, 5] },
result: 15,
}) */
const prettify = value => JSON.stringify(value, null, 2)
const Assertion = (func, result, ...args) => async function test() {
const evaluatedResult = await func(...args)
if (isDeepEqual(result, evaluatedResult)) {
return undefined
}
throw new AssertionError(`
${func.toString()}
args - ${prettify(args)}
expected - ${prettify(result)}
actual - ${prettify(evaluatedResult)}
`)
}
const binaryToReadableStream = function (binary) {
return new Readable({
read() {
this.push(binary)
this.push(null)
},
})
}
const arrayToObjectReadableStream = function (array) {
return new Readable({
objectMode: true,
read() {
for (const item of array) {
this.push(item)
}
this.push(null)
},
})
}
const MockWritable = function (array = []) {
Writable.call(this)
this.array = array
this.handlers = new Map()
}
MockWritable.prototype = {
write(chunk, encoding, callback) {
this.array.push(chunk)
},
on(eventName, handler) {
if (this.handlers.has(eventName)) {
this.handlers.get(eventName).push(handler)
} else {
this.handlers.set(eventName, [handler])
}
},
once(eventName, handler) {
this.handlers.set(eventName, [handler])
},
emit(eventName, ...args) {
if (!this.handlers.has(eventName)) {
return undefined
}
return this.handlers.get(eventName).map(handler => handler(...args))
}
}
const MockDuplexStream = function (values) {
MockWritable.call(this)
this.values = [...values]
}
MockDuplexStream.prototype = {
...MockWritable.prototype,
async* [symbolAsyncIterator]() {
for (const item of this.values) {
yield item
}
},
}
const AsyncMockFoldable = function (values) {
this.values = values
}
AsyncMockFoldable.prototype = {
async reduce(reducer, init) {
return this.values.reduce(reducer, init)
},
}
const MockFoldable = function (values) {
this.values = values
}
MockFoldable.prototype = {
reduce(reducer, init) {
return this.values.reduce(reducer, init)
},
}
describe('rubico', () => {
describe('pipe', () => {
it('behaves eagerly when passed any amount of arguments before the array of functions', async () => {
const array = pipe(1, 2, 3, [
Array.of,
numbers => numbers.map(number => number * 3),
])
assert.deepEqual(array, [3, 6, 9])
})
it('behaves eagerly and resolves any amount of Promise arguments before the array of functions', async () => {
const array = await pipe(Promise.resolve(1), 2, Promise.resolve(3), [
Array.of,
numbers => numbers.map(number => number * 3),
])
assert.deepEqual(array, [3, 6, 9])
})
it('chains async and regular functions together', async () => {
ase(await pipe([hi, ho, asyncHey])('yo'), 'yohihohey')
})
it('does something without arguments', async () => {
ase(await pipe([hi, ho, asyncHey])(), 'undefinedhihohey')
})
it('chaining one fn is the same as just calling that fn', async () => {
ase(await pipe([asyncHey])('yo'), await asyncHey('yo'))
})
it('returns the raw value (no promise required) if all functions are sync', async () => {
ase(pipe([hi, hi, hi])('yo'), 'yohihihi')
})
it('returns a promise if any fns async', async () => {
aok(pipe([hi, hi, hi, asyncHey])('yo') instanceof Promise)
})
it('pipe(Array<GeneratorFunction>)(Generator)', async () => {
const numbersGen = function* () {
yield 1; yield 2; yield 3; yield 4; yield 5
}
const isOddGen = function* (iter) {
for (const item of iter) {
if (item % 2 == 1) yield item
}
}
const squareGen = function* (iter) {
for (const item of iter) {
yield item ** 2
}
}
const iter = pipe([isOddGen, squareGen])(numbersGen())
const arr = [...iter]
assert.deepEqual(arr, [1, 9, 25])
})
it('pipe(Array<AsyncGeneratorFunction>)(AsyncGenerator)', async () => {
const asyncNumbersGen = async function* () {
yield 1; yield 2; yield 3; yield 4; yield 5
}
const isOddGen = async function* (iter) {
for await (const item of iter) {
if (item % 2 == 1) yield item
}
}
const squareGen = async function* (iter) {
for await (const item of iter) {
yield item ** 2
}
}
const iter = pipe([isOddGen, squareGen])(asyncNumbersGen())
const arr = []
for await (const item of iter) arr.push(item)
assert.deepEqual(arr, [1, 9, 25])
})
it('throws a TypeError if first argument not an array', async () => {
assert.throws(
() => {
pipe(() => 1, undefined, () => 2)()
},
new TypeError('funcs.reduce is not a function')
)
})
it('throws a TypeError if passed less than one function', async () => {
assert.throws(
() => pipe([])(),
new TypeError('Reduce of empty array with no initial value'),
)
})
it('throws a TypeError if any arguments are not a function', async () => {
assert.throws(
() => {
pipe([() => 1, undefined, () => 2])()
},
new TypeError('funcB is not a function'),
)
})
it('handles sync errors', async () => {
assert.throws(
() => pipe([hi, hi, x => { throw new Error(`throwing ${x}`) }])('yo'),
new Error('throwing yohihi'),
)
})
it('handles async errors', async () => {
assert.rejects(
() => pipe([hi, asyncHey, x => { throw new Error(`throwing ${x}`) }])('yo'),
new Error('throwing yohihey'),
)
})
})
describe('compose', () => {
it('chains functions in reverse', async () => {
ade(
compose([1, 2, 3, 4, 5], [
map(number => number ** 2),
map(number => number + 2),
filter(number => number % 2 == 1)
]),
[9, 25, 49],
)
ade(
compose([
map(number => number ** 2),
map(number => number + 2),
filter(number => number % 2 == 1)
])([1, 2, 3, 4, 5]),
[9, 25, 49],
)
ade(
await compose([
map(async number => number ** 2),
map(number => number + 2),
filter(async number => number % 2 == 1)
])([1, 2, 3, 4, 5]),
[9, 25, 49],
)
ade(
await compose(Promise.resolve([1, 2, 3, 4, 5]), [
map(number => number ** 2),
map(number => number + 2),
filter(number => number % 2 == 1)
]),
[9, 25, 49],
)
})
})
describe('all', () => {
it('API coverage', async () => {
ade(
all(1, 2, 3, [
Array.of,
Array.of,
Array.of,
]),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
],
)
ade(
all([
Array.of,
Array.of,
Array.of,
])(1, 2, 3),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
],
)
ade(
all([
Array.of,
Array.of,
Array.of,
4,
])(1, 2, 3),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
4,
],
)
ade(
await all(Promise.resolve(1), 2, Promise.resolve(3), [
Array.of,
Array.of,
Array.of,
]),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
],
)
ade(
all(1, 2, 3, {
a: Array.of,
b: Array.of,
c: Array.of,
}),
{
a: [1, 2, 3],
b: [1, 2, 3],
c: [1, 2, 3],
},
)
ade(
all({
a: Array.of,
b: Array.of,
c: Array.of,
})(1, 2, 3),
{
a: [1, 2, 3],
b: [1, 2, 3],
c: [1, 2, 3],
},
)
ade(
await all(Promise.resolve(1), 2, Promise.resolve(3), {
a: Array.of,
b: Array.of,
c: Array.of,
}),
{
a: [1, 2, 3],
b: [1, 2, 3],
c: [1, 2, 3],
},
)
ade(
all({
a: Array.of,
b: Array.of,
c: Array.of,
d: 4,
})(1, 2, 3),
{
a: [1, 2, 3],
b: [1, 2, 3],
c: [1, 2, 3],
d: 4,
},
)
})
it('maps input to array of sync functions', async () => {
ade(all([hi, hi, hi])('hi'), ['hihi', 'hihi', 'hihi'])
})
it('maps input to object of sync functions', async () => {
ade(
all({ a: hi, b: hi, c: hi })('hi'),
{ a: 'hihi', b: 'hihi', c: 'hihi' },
)
})
it('maps input to array of async functions', async () => {
aok(all([asyncHey, asyncHey, asyncHey])('hi') instanceof Promise)
ade(
await all([asyncHey, asyncHey, asyncHey])('hey'),
['heyhey', 'heyhey', 'heyhey'],
)
})
it('maps input to object of async functions', async () => {
aok(all({ a: asyncHey, b: asyncHey, c: asyncHey })('yo') instanceof Promise)
ade(
await all({ a: asyncHey, b: asyncHey, c: asyncHey })('hey'),
{ a: 'heyhey', b: 'heyhey', c: 'heyhey' },
)
})
it('any functions async => Promise', async () => {
aok(all([asyncHey, asyncHey, hi])('1') instanceof Promise)
ade(
await all([asyncHey, asyncHey, hi])('1'),
['1hey', '1hey', '1hi'],
)
})
it('only nonfunctions', async () => {
ade(all([1, 2, 3]), [1, 2, 3])
ade(await all(Promise.resolve([Promise.resolve(1), 2, 3])), [1, 2, 3])
ade(await all([Promise.resolve(1), Promise.resolve(2), 3]), [1, 2, 3])
ade(all([]), [])
ade(all({ a: 1, b: 2, c: 3 }), { a: 1, b: 2, c: 3 })
ade(await all(Promise.resolve({
a: Promise.resolve(1),
b: 2,
c: 3,
})), { a: 1, b: 2, c: 3 })
ade(await all({
a: Promise.resolve(1),
b: Promise.resolve(2),
c: 3,
}), { a: 1, b: 2, c: 3 })
ade(all({}), {})
})
})
describe('all.series', () => {
it('API coverage', async () => {
ade(
all.series(1, 2, 3, [
Array.of,
Array.of,
Array.of,
]),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
],
)
ade(
all.series([
Array.of,
Array.of,
Array.of,
])(1, 2, 3),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
],
)
ade(
await all.series(Promise.resolve(1), 2, Promise.resolve(3), [
Array.of,
Array.of,
Array.of,
]),
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
],
)
})
it('evaluates input against array of functions in series (sync)', async () => {
const arr = []
ade(
all.series([
() => { arr.push(1); return 'a' },
() => { arr.push(2); return 'b' },
() => { arr.push(3); return 'c' },
])(),
['a', 'b', 'c']
)
ade(arr, [1, 2, 3])
})
it('evaluates input against array of functions in series (async)', async () => {
const arr = []
const staggeredPush = all.series([
() => sleep(10).then(() => { arr.push(1); return 'a' }),
() => sleep(5).then(() => { arr.push(2); return 'b' }),
() => { arr.push(3); return 'c' },
])()
aok(staggeredPush instanceof Promise)
ade(await staggeredPush, ['a', 'b', 'c'])
ade(arr, [1, 2, 3])
const arr2 = []
const parallelPush = all([
() => sleep(10).then(() => { arr2.push(1); return 'a' }),
() => sleep(5).then(() => { arr2.push(2); return 'b' }),
() => { arr2.push(3); return 'c' },
])()
aok(parallelPush instanceof Promise)
ade(await parallelPush, ['a', 'b', 'c'])
ade(arr2, [3, 2, 1])
})
it('throws TypeError for all([])', async () => {
assert.deepEqual(all.series([])(), [])
})
it('throws TypeError for all([nonFunction])', async () => {
assert.throws(
() => all.series(['hey'])(),
new TypeError('funcs[funcsIndex] is not a function')
)
})
})
describe('assign', () => {
it('API coverage', async () => {
ade(await assign({}, {
a: () => 1,
b: () => 2,
c: () => 3,
e: 4,
f: Promise.resolve(5),
}), { a: 1, b: 2, c: 3, e: 4, f: 5 })
ade(assign({
a: () => 1,
b: () => 2,
c: () => 3,
})({}), { a: 1, b: 2, c: 3 })
ade(await assign(Promise.resolve({}), {
a: () => 1,
b: () => 2,
c: () => 3,
}), { a: 1, b: 2, c: 3 })
})
it('maps input to object of sync functions then merges', async () => {
ade(
assign({
b: x => `${x.a}yo`,
c: x => `${x.a}yaya`,
})({ a: 'a' }),
{ a: 'a', b: 'ayo', c: 'ayaya' },
)
})
it('maps input to object of async functions then merges', async () => {
aok(assign({
b: async x => `${x.a}yo`,
c: async x => `${x.a}yaya`,
})({ a: 'a' }) instanceof Promise)
ade(
await assign({
b: async x => `${x.a}yo`,
c: async x => `${x.a}yaya`,
})({ a: 'a' }),
{ a: 'a', b: 'ayo', c: 'ayaya' },
)
})
it('assign(Set)(nonObject) -> {}', async () => {
assert.deepEqual(assign(new Set(['hey']))(), {})
})
it('assign(...)(string) -> { 0: s, 1: t, ... }', async () => {
assert.deepEqual(
assign({ a: value => value })('hi'),
{ '0': 'h', '1': 'i', a: 'hi' },
)
})
})
describe('tap', () => {
it('[sync] calls a provided function with input, returning input', async () => {
ase(tap(x => x + 1)(1), 1)
})
it('[async] calls a provided function with input, returning input', async () => {
aok(tap(async x => x + 1)(1) instanceof Promise)
ase(await tap(async x => x + 1)(1), 1)
})
it('Promise arguments', async () => {
const arr = []
await tap(Promise.resolve(1), Promise.resolve(2), 3, (a, b, c) => {
arr.push(a, b, c)
})
assert.deepEqual(arr, [1, 2, 3])
})
it('multiple arguments', async () => {
const array = []
const point = tap((...args) => (array.push(...args)))(1, 2, 3, 4, 5)
assert.strictEqual(point, 1)
assert.deepEqual(array, [1, 2, 3, 4, 5])
})
it('eager API', async () => {
let val = null
tap('a', 'b', 'c', (...args) => {
val = args
})
assert.deepEqual(val, ['a', 'b', 'c'])
})
})
describe('tap.if', () => {
describe('tap.if(condition, f); conditional tap; only calls fn on truthy condition', () => {
it('sync', async () => {
const isOdd = x => x % 2 === 1
const oddNumbers = []
const pushOddNumbers = number => oddNumbers.push(number)
const numbers = [1, 2, 3, 4, 5]
numbers.forEach(number => {
assert.strictEqual(tap.if(isOdd, pushOddNumbers)(number), number)
})
assert.deepEqual(oddNumbers, [1, 3, 5])
tap.if(7, isOdd, pushOddNumbers)
assert.deepEqual(oddNumbers, [1, 3, 5, 7])
await tap.if(Promise.resolve(9), isOdd, pushOddNumbers)
assert.deepEqual(oddNumbers, [1, 3, 5, 7, 9])
})
it('async', async () => {
const isOdd = x => x % 2 === 1
const oddNumbers = []
const pushOddNumbers = number => oddNumbers.push(number)
const numbers = [1, 2, 3, 4, 5]
for (const number of numbers) {
assert.strictEqual(await tap.if(async(isOdd), pushOddNumbers)(number), number)
}
assert.deepEqual(oddNumbers, [1, 3, 5])
for (const number of numbers) {
assert.strictEqual(await tap.if(isOdd, delay(pushOddNumbers, 10))(number), number)
}
assert.deepEqual(oddNumbers, [1, 3, 5, 1, 3, 5])
})
})
})
describe('tryCatch', () => {
it('behaves eagerly when supplied any amount of arguments before the tryer and catcher', async () => {
const add = (a, b) => a + b
let sum = null
tryCatch(1, 2, 3, function throwSum(...numbers) {
const sum = numbers.reduce(add)
throw new Error(`${sum}`)
}, function logErrorMessage(error) {
sum = Number(error.message)
})
assert.equal(sum, 6)
})
it('behaves eagerly when supplied any amount of Promise arguments before the tryer and catcher', async () => {
const add = (a, b) => a + b
let sum = null
await tryCatch(Promise.resolve(1), 2, Promise.resolve(3), function throwSum(...numbers) {
const sum = numbers.reduce(add)
throw new Error(`${sum}`)
}, function logErrorMessage(error) {
sum = Number(error.message)
})
assert.equal(sum, 6)
})
it('async eager tryCatch', async () => {
const add = (a, b) => a + b
let sum = null
await tryCatch(1, 2, 3, async function throwSum(...numbers) {
const sum = numbers.reduce(add)
throw new Error(`${sum}`)
}, async function logErrorMessage(error) {
sum = Number(error.message)
})
assert.equal(sum, 6)
})
it('tries a sync function and catches with a sync function', async () => {
const errProp = (err, x) => { err.x = x; return err }
const throwError = x => { throw new Error(x) }
ase(tryCatch(x => x + 1, errProp)(1), 2)
const e1 = tryCatch(throwError, errProp)(1)
aok(e1 instanceof Error)
ase(e1.name, 'Error')
ase(e1.message, '1')
ase(e1.x, 1)
})
it('tries an async function and catches with a sync function', async () => {
const errProp = (err, x) => { err.x = x; return err }
const asyncThrowError = async x => { throw new Error(x) }
const reject = x => Promise.reject(new Error(x))
aok(tryCatch(async x => x + 1, errProp)(1) instanceof Promise)
ase(await tryCatch(async x => x + 1, errProp)(1), 2)
aok(tryCatch(asyncThrowError, errProp)(1) instanceof Promise)
const e1 = await tryCatch(asyncThrowError, errProp)(1)
aok(e1 instanceof Error)
ase(e1.name, 'Error')
ase(e1.message, '1')
ase(e1.x, 1)
aok(tryCatch(reject, errProp)(1) instanceof Promise)
const e2 = await tryCatch(reject, errProp)(1)
aok(e2 instanceof Error)
ase(e2.name, 'Error')
ase(e2.message, '1')
ase(e2.x, 1)
})
it('tries a sync function and catches with an async function', async () => {
const asyncErrProp = async (err, x) => { err.x = x; return err }
const throwError = x => { throw new Error(x) }
ase(tryCatch(x => x + 1, asyncErrProp)(1), 2)
aok(tryCatch(throwError, asyncErrProp)(1) instanceof Promise)
const e1 = await tryCatch(throwError, asyncErrProp)(1)
aok(e1 instanceof Error)
ase(e1.name, 'Error')
ase(e1.message, '1')
ase(e1.x, 1)
})
it('tries an async function and catches with an async function', async () => {
const asyncErrProp = async (err, x) => { err.x = x; return err }
const asyncThrowError = async x => { throw new Error(x) }
const reject = x => Promise.reject(new Error(x))
aok(tryCatch(async x => x + 1, asyncErrProp)(1) instanceof Promise)
ase(await tryCatch(async x => x + 1, asyncErrProp)(1), 2)
aok(tryCatch(asyncThrowError, asyncErrProp)(1) instanceof Promise)
const e1 = await tryCatch(asyncThrowError, asyncErrProp)(1)
aok(e1 instanceof Error)
ase(e1.name, 'Error')
ase(e1.message, '1')
ase(e1.x, 1)
aok(tryCatch(reject, asyncErrProp)(1) instanceof Promise)
const e2 = await tryCatch(reject, asyncErrProp)(1)
aok(e2 instanceof Error)
ase(e2.name, 'Error')
ase(e2.message, '1')
ase(e2.x, 1)
})
it('throws a TypeError if passed a non function tryer', async () => {
assert.deepEqual(
tryCatch('hey', (...args) => args)('sup'),
[new TypeError('tryer is not a function'), 'sup'],
)
})
it('won\'t enforce the catcher function typecheck', async () => {
assert.deepEqual(
tryCatch(() => 'ayo', Buffer.from('abc'))('hey'),
'ayo',
)
})
})
describe('switchCase', () => {
it('API coverage', async () => {
ase(
switchCase(1, [
x => x === 1, () => 'hi',
x => x === 2, () => 'ho',
() => 'hey',
]),
'hi',
)
ase(
await switchCase(Promise.resolve(1), [
x => x === 1, () => 'hi',
x => x === 2, () => 'ho',
() => 'hey',
]),
'hi',
)
})
it('switches on values (including Promises), evaluating eagerly', async () => {
ase(switchCase([true, 'hey', 'ho']), 'hey')
ase(await switchCase([
Promise.resolve(true),
Promise.resolve('hey'),
'ho',
]), 'hey')
ase(await switchCase([
true,
Promise.resolve('hey'),
'ho',
]), 'hey')
ase(await switchCase([
false,
Promise.resolve('hey'),
'ho',
]), 'ho')
ase(await switchCase([
false,
Promise.resolve('hey'),
Promise.resolve('ho'),
]), 'ho')
ase(switchCase([false, 'hey', false, 'ho', 'default']), 'default')
ase(switchCase([false, 'hey', false, 'hey', true, 'ho']), 'ho')
ase(switchCase([false, 'hey', false, 'hey', false, 'ho']), undefined)
})
it('defaults with undefined for an even number of cases', async () => {
ase(switchCase([false, 'hey', false, 'hey', false, 'hey']), undefined)
})
it('switches on provided sync functions', async () => {
ase(
switchCase([
x => x === 1, () => 'hi',
x => x === 2, () => 'ho',
() => 'hey',
])(1),
'hi',
)
ase(
switchCase([
x => x === 1, () => 'hi',
x => x === 2, () => 'ho',
() => 'hey',
])(2),
'ho',
)
ase(
switchCase([
x => x === 1, () => 'hi',
x => x === 2, () => 'ho',
() => 'hey',
])(3),
'hey',
)
ase(
switchCase([
x => x === 1, async () => 'hi',
x => x === 2, async () => 'ho',
() => 'hey',
])(3),
'hey',
)
})
it('switches on provided async functions or values', async () => {
aok(
switchCase([
async x => x === 1, async () => 'hi',
async x => x === 2, async () => 'ho',
async () => 'hey',
])(1) instanceof Promise,
)
aok(
switchCase([
async x => x === 1, () => 'hi',
x => x === 2, () => 'ho',
() => 'hey',
])(1) instanceof Promise,
)
ase(
await switchCase([
async x => x === 1, async () => 'hi',
async x => x === 2, async () => 'ho',
async () => 'hey',
])(1),
'hi',
)