-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
1565 lines (1346 loc) · 34.7 KB
/
index.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
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
export default {
defer,
deferSet,
delay,
delayChain,
each,
filter,
flatMap,
funnel,
inspect,
map,
once,
props,
reduce,
rethrow,
retry,
some,
specific,
tap,
wrapFunction,
};
/**
* IfPromise< P, T[, U] > returns T if P is a promise, otherwise returns U (or
* fallbacks to <never> ).
*/
export type IfPromise< P, T, U = never > =
P extends Promise< infer _X > ? T : U;
/**
* IfNotPromise< P, T[, U] > returns U (fallbacks to <never>) if P is a
* promise, otherwise returns T.
*/
export type IfNotPromise< P, T, U = never > =
P extends Promise< infer _X > ? U : T;
/**
* Returns the Promise wrapped value of P, unless it's already a promise, where
* the promise itself is returned instead.
*
* For P being Promise<E>, it returns P
* For non-promise P, it returns Promise<P>
*/
export type PromiseOf< P > = P extends Promise< infer _U > ? P : Promise< P >;
/**
* Returns the element type of a promise, or the type itself if it isn't
* wrapped in a promise.
*
* For P being Promise<E>, it returns E
* For non-promise P, it returns P
*/
export type PromiseElement< P > = P extends Promise< infer U > ? U : P;
/**
* Given type P, returns the same type P if it is a Promise, otherwise never.
*/
export type EnsurePromise< P > = P extends Promise< infer _U > ? P : never;
/**
* Given type T, returns the same type T if it is *not* a Promise, otherwise
* never.
*/
export type EnsureNotPromise< T > = T extends Promise< infer _U > ? never : T;
function toReadonlyArray< T >( arr: ConcatArray< T > ): ReadonlyArray< T >
{
/* istanbul ignore else */
if ( typeof ( < ReadonlyArray< T > >arr ).map === "function" )
return < ReadonlyArray< T > >arr;
else
return Array.from( arr );
}
type ConcurrentQueueRunner< R > = ( ) => R | PromiseLike< R >;
interface ConcurrentQueueItem< R >
{
cb: ConcurrentQueueRunner< R >;
deferred: Deferred< R >;
}
interface ConcurrentQueue< R >
{
size: number;
count: number;
queue: Array< ConcurrentQueueItem< R > >;
process: any;
runOne: ( cb: ConcurrentQueueRunner< R > ) => Promise< R >;
enqueue: ( cb: ConcurrentQueueRunner< R > ) => Promise< R >;
}
export type Callback< R, A extends any[ ] > =
( ...args: A ) => Promise< R >;
/**
* Create a maximum concurrency for fn (can be curried)
*
* Either specify fn and invoke the returned function, or skip fn and the
* returned function will take an arbitrary function to limit concurrency for.
*
* @param size Concurrency limit
* @param fn The function to limit the concurrency for
* @returns Concurrency-limited version of fn
*/
export function concurrent< R, A extends any[ ] >(
size: number,
fn: Callback< R, A >
): ( ...a: A ) => Promise< R >;
export function concurrent( size: number )
: < R, A extends any[ ] >( fn: Callback< R, A >, ...a: A ) => Promise< R >;
export function concurrent< R, A extends any[ ] >(
size: number,
fn?: Callback< R, A >
)
{
const queue = makeQueue< R >( size );
if ( size < 1 )
throw new RangeError( `Size must be at least 1` );
if ( !fn )
return ( cb: Callback< R, A >, ...args: A ) =>
queue.enqueue( ( ) => cb( ...args ) );
else
return ( ...args: A ): Promise< R > =>
queue.enqueue( ( ) => fn( ...args ) );
}
function makeQueue< R >( size: number ): ConcurrentQueue< R >
{
const queue: ConcurrentQueue< R > = {
size,
count: 0,
queue: [ ],
process: ( ) =>
{
if ( queue.queue.length )
{
const first = queue.queue.shift( )!;
const { cb, deferred } = first;
queue.runOne( cb ).then( deferred.resolve, deferred.reject );
}
},
runOne: ( cb: ConcurrentQueueRunner< R > ) =>
{
++queue.count;
return ( async ( ) => cb( ) )( )
.finally( ( ) =>
{
--queue.count;
queue.process( );
} );
},
enqueue: async ( cb: ConcurrentQueueRunner< R > ) =>
{
if ( queue.count >= queue.size )
{
const deferred = defer< R >( );
queue.queue.push( { cb, deferred } );
return deferred.promise;
}
return queue.runOne( cb );
}
};
return queue;
}
export function delay( milliseconds: number ): Promise< void >;
export function delay< T >( milliseconds: number, t: T ): Promise< T >;
export function delay< T >( milliseconds: number, t?: T )
: Promise< void > | Promise< T >
{
return new Promise< T >( resolve =>
{
setTimeout( ( ) => resolve( t as T ), milliseconds );
} );
}
export function delayChain( milliseconds: number )
: < T >( t: T ) => Promise< T >
{
return tap( ( ) => delay( milliseconds ) );
}
export function tap<
U,
Fn extends ( t: U ) => ( void | PromiseLike< void > )
>( fn: Fn )
: ( u: U ) => Promise< U >
{
return async ( t: U ): Promise< U > =>
{
await fn( t );
return t;
};
}
export function props( obj: any ): Promise< any >
{
const ret: any = { };
const awaiters = [ ];
for ( const prop of Object.keys( obj ) )
awaiters.push(
Promise.resolve( obj[ prop ] )
.then( val => { ret[ prop ] = val; } )
);
return Promise.all( awaiters ).then( ( ) => ret );
}
export interface ConcurrencyOptions
{
concurrency: number;
}
export interface ChunkOptions
{
chunk: number | 'idle';
}
export type FilterMapOptions = Partial< ConcurrencyOptions | ChunkOptions >;
const defaultFilterMapOptions: FilterMapOptions = {
concurrency: Infinity
};
export type MapArray< T > =
Array< T | PromiseLike< T > > |
ConcatArray< T | PromiseLike< T > >;
export type MapFn< T, U > =
( t: T, index: number, arr: MapArray< T > ) =>
U | Promise< U >;
export type FlatMapFn< T, U > =
( t: T, index: number, arr: MapArray< T > ) =>
| U
| ConcatArray< U | Promise< U > >
| Array< U | Promise< U > >
| Promise<
| U
| ConcatArray< U | Promise< U > >
| Array< U | Promise< U > >
>;
export type FilterFn< T > = MapFn< T, boolean >;
export function filter< T >( filterFn: FilterFn< T > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > >;
export function filter< T >( opts: FilterMapOptions, filterFn: FilterFn< T > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > >;
export function filter< T >(
arr: ConcatArray< T | PromiseLike< T > >,
filterFn: FilterFn< T >
): Promise< Array< T > >;
export function filter< T >(
arr: ConcatArray< T | PromiseLike< T > >,
opts: FilterMapOptions,
filterFn: FilterFn< T >
): Promise< Array< T > >;
export function filter< T >(
arr: ConcatArray< T | PromiseLike< T > > | FilterFn< T > | FilterMapOptions,
opts?: FilterFn< T > | FilterMapOptions,
filterFn?: FilterFn< T >
)
:
( ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > > ) |
( Promise< Array< T > > )
{
if ( Array.isArray( arr ) )
{
if ( typeof opts === "function" )
{
filterFn = opts;
opts = defaultFilterMapOptions;
}
const intermediate =
filter( < FilterMapOptions >opts, < FilterFn< T > >filterFn );
return intermediate( arr );
}
filterFn = typeof arr === "function" ? arr : < FilterFn< T > >opts;
opts =
typeof arr === "function"
? defaultFilterMapOptions
: < FilterMapOptions >arr;
const wrappedFilterFn =
( val: T, index: number, arr: MapArray< T > ) =>
Promise.resolve( ( < FilterFn< T > >filterFn )( val, index, arr ) )
.then( ok => ( { ok, val } ) );
return ( t: ConcatArray< T | PromiseLike< T > > ): Promise< Array< T > > =>
{
return map( < FilterMapOptions >opts, wrappedFilterFn )( t )
.then( values =>
values
.filter( ( { ok } ) => ok )
.map( ( { val } ) => val )
);
};
}
export function map< T, U >( mapFn: MapFn< T, U > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< U > >;
export function map< T, U >( opts: FilterMapOptions, mapFn: MapFn< T, U > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< U > >;
export function map< T, U >(
arr: ConcatArray< T | PromiseLike< T > >,
mapFn: MapFn< T, U >
): Promise< Array< U > >;
export function map< T, U >(
arr: ConcatArray< T | PromiseLike< T > >,
opts: FilterMapOptions,
mapFn: MapFn< T, U >
): Promise< Array< U > >;
export function map< T, U >(
arr:
ConcatArray< T | PromiseLike< T > > |
MapFn< T, U > |
FilterMapOptions,
opts?: MapFn< T, U > | FilterMapOptions,
mapFn?: MapFn< T, U >
)
:
( ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< U > > ) |
( Promise< Array< U > > )
{
if ( Array.isArray( arr ) )
{
if ( typeof opts === "function" )
{
mapFn = opts;
opts = defaultFilterMapOptions;
}
return map( < FilterMapOptions >opts, < MapFn< T, U > >mapFn )( arr );
}
mapFn = typeof arr === "function" ? arr : < MapFn< T, U > >opts;
opts =
typeof arr === "function"
? defaultFilterMapOptions
: < FilterMapOptions >arr;
const promiseMapFn =
( t: T, index: number, arr: ConcatArray< T | PromiseLike< T > > ) =>
Promise.resolve( ( < MapFn< T, U > >mapFn )( t, index, arr ) );
const { concurrency = Infinity } = opts as Partial< ConcurrencyOptions >;
const { chunk } = opts as Partial< ChunkOptions >;
if ( typeof chunk !== 'undefined' )
{
if ( typeof chunk !== 'number' && chunk !== 'idle' )
throw new Error( `Invalid 'chunk' option to 'map': ${chunk}` );
const useIdle = chunk === 'idle';
const timeout =
chunk === 'idle'
? 15 // 15ms, allow 1.666ms for browser work (to fill up 16.666 ms)
: chunk;
const looper = async ( cb: ( timeout: number ) => Promise< void > ) =>
new Promise< void >( ( resolve, reject ) =>
{
const resolver = async ( timeout: number ) =>
{
try
{
await cb( timeout );
resolve( );
}
catch ( err )
{
reject( err );
}
}
( useIdle && typeof requestIdleCallback !== 'undefined' )
? requestIdleCallback(
idleDeadline =>
resolver(
// Round down to millisecond, subtract 1.
// That gives a little bit of time for the browser
// to do whatever it wants, and will to some
// degree prevent us to step over the time budget.
Math.floor( idleDeadline.timeRemaining( ) ) - 1
),
{ timeout: 0 }
)
: setTimeout( ( ) => resolver( timeout ), 0 );
} );
return ( t: ConcatArray< T | PromiseLike< T > > )
: Promise< Array< U > > =>
{
return Promise.resolve( t )
.then( async ( values: ConcatArray< T | PromiseLike< T > > ) =>
{
const arr = toReadonlyArray( values );
const ret: Array< U > = [ ];
let i = 0;
const loop = async ( timeout: number ) =>
{
const start = Date.now( );
for ( ; i < arr.length; )
{
const u = await promiseMapFn( await arr[ i ], i, arr );
ret.push( u );
++i;
if ( Date.now( ) - start >= timeout )
{
await looper( loop );
break;
}
}
}
await loop( timeout );
return ret;
} )
.then( values => Promise.all( values ) );
};
}
const concurrently = concurrent( concurrency );
return ( t: ConcatArray< T | PromiseLike< T > > )
: Promise< Array< U > > =>
{
return Promise.resolve( t )
.then( ( values: ConcatArray< T | PromiseLike< T > > ) =>
toReadonlyArray( values )
.map( ( val, index, arr ) =>
( ( ) => Promise.resolve( val ) )( )
.then( ( val: T ) =>
concurrently( promiseMapFn, val, index, arr )
)
)
)
.then( values => Promise.all( values ) );
};
}
export function flatMap< T, U >( mapFn: FlatMapFn< T, U > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< U > >;
export function flatMap< T, U >(
opts: FilterMapOptions, mapFn: FlatMapFn< T, U >
): ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< U > >;
export function flatMap< T, U >(
arr: ConcatArray< T | PromiseLike< T > >,
mapFn: FlatMapFn< T, U >
): Promise< Array< U > >;
export function flatMap< T, U >(
arr: ConcatArray< T | PromiseLike< T > >,
opts: FilterMapOptions,
mapFn: FlatMapFn< T, U >
): Promise< Array< U > >;
export function flatMap< T, U >(
arr:
ConcatArray< T | PromiseLike< T > > |
FlatMapFn< T, U > |
FilterMapOptions,
opts?: FlatMapFn< T, U > | FilterMapOptions,
mapFn?: FlatMapFn< T, U >
)
:
( ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< U > > ) |
( Promise< Array< U > > )
{
if ( Array.isArray( arr ) )
{
return map(
arr,
opts as FilterMapOptions,
mapFn as FlatMapFn< T, U >
)
.then( arr =>
Promise.all(
arr
.map( inner => Array.isArray( inner ) ? inner : [ inner ] )
.flat( 1 ) as Array< U | Promise< U > >
)
);
}
return async ( t: ConcatArray< T | PromiseLike< T > > )
: Promise< Array< U > > =>
{
return flatMap(
t,
arr as FilterMapOptions,
opts as FlatMapFn< T, U >
);
};
}
export type SyncReduceInput< T > = Iterable< T | PromiseLike< T > >;
export type ReduceInput< T > =
SyncReduceInput< T > |
PromiseLike< SyncReduceInput< T > >;
export type ReduceFunction< T, R > =
( accumulator: R, current: T, index: number, length: number ) =>
R | PromiseLike< R >;
export async function reduce< T, R >(
input: ReduceInput< T >,
reducer: ReduceFunction< T, R >
)
: Promise< R | undefined >;
export async function reduce< T, R >(
input: ReduceInput< T >,
reducer: ReduceFunction< T, R >,
initialValue: R | PromiseLike< R >
)
: Promise< R >;
export function reduce< T, R >(
reducer: ReduceFunction< T, R >
)
: < U extends SyncReduceInput< T > >( input: U ) => Promise< R | undefined >;
export function reduce< T, R >(
reducer: ReduceFunction< T, R >,
initialValue: R | PromiseLike< R >
)
: < U extends SyncReduceInput< T > >( input: U ) => Promise< R >;
export function reduce< T, R >(
input: ReduceInput< T > | ReduceFunction< T, R >,
reducer?: ReduceFunction< T, R > | R | PromiseLike< R >,
initialValue?: R | PromiseLike< R >
)
:
( Promise< R | undefined > )
|
( < U extends SyncReduceInput< T > >( input: U ) =>
Promise< R | undefined >
)
{
if ( typeof input === "function" )
{
initialValue = < R >reducer;
const _reducer = < ReduceFunction< T, R > >input;
return async < U extends SyncReduceInput< T > >( input: U ) =>
{
return reduceImpl( input, _reducer, initialValue );
};
}
return reduceImpl(
< ReduceInput< T > >input,
< ReduceFunction< T, R > >reducer,
initialValue
);
}
async function reduceImpl< T, R >(
input: ReduceInput< T >,
reducer: ReduceFunction< T, R >,
initialValue?: R | PromiseLike< R >
)
: Promise< R | undefined >
{
const _input = Array.from< T | PromiseLike< T > >( await input );
const _initialValue = await initialValue;
if ( _input.length === 0 )
return _initialValue;
const usingInitialValue = typeof _initialValue !== "undefined";
const length = _input.length;
let index = usingInitialValue ? 0 : 1;
let accumulator: R =
usingInitialValue
? < R >_initialValue
// This cast should be safe if the interface is respected
: < R >< any >await _input.shift( );
while ( _input.length > 0 )
accumulator = await reducer(
accumulator, < T >await _input.shift( ), index++, length );
return accumulator;
}
const defaultEachOptions: FilterMapOptions = {
concurrency: 1
};
export type EachFn< T > =
( t: T, index: number, length: number ) => void | Promise< void >;
export function each< T >( eachFn: EachFn< T > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > >;
export function each< T >( opts: FilterMapOptions, eachFn: EachFn< T > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > >;
export function each< T >(
arr: ConcatArray< T | PromiseLike< T > >,
eachFn: EachFn< T >
): Promise< Array< T > >;
export function each< T >(
arr: ConcatArray< T | PromiseLike< T > >,
opts: FilterMapOptions,
eachFn: EachFn< T >
): Promise< Array< T > >;
export function each< T >(
arr: ConcatArray< T | PromiseLike< T > > | EachFn< T > | FilterMapOptions,
opts?: EachFn< T > | FilterMapOptions,
eachFn?: EachFn< T >
)
:
( ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > > ) |
( Promise< Array< T > > )
{
if ( Array.isArray( arr ) )
{
if ( typeof opts === "function" )
{
eachFn = opts;
opts = defaultEachOptions;
}
const _opts = < FilterMapOptions >opts;
return eachImpl( _opts, eachFn! )( arr );
}
if ( typeof arr === "function" )
{
eachFn = arr;
opts = defaultEachOptions;
}
else
{
eachFn = opts as EachFn< T >;
opts = arr as FilterMapOptions;
}
const _opts = < FilterMapOptions >opts;
return eachImpl( _opts, eachFn! );
}
function eachImpl< T >( opts: FilterMapOptions, eachFn: EachFn< T > )
: ( t: ConcatArray< T | PromiseLike< T > > ) => Promise< Array< T > >
{
return async ( arr: ConcatArray< T | PromiseLike< T > > )
: Promise< Array< T > > =>
{
const length = arr.length;
async function iterator( t: T, index: number )
{
await eachFn( t, index, length );
return t;
}
return map( arr, opts, iterator );
};
}
export type SomeReturn< R > = Promise< R | false >;
export type SomeSyncReturn< R > = SomeReturn< R > | R | false;
export type SomePredicate< T, R > = ( t: T ) => SomeSyncReturn< R >;
export type SomeArray< T > =
ConcatArray< T | PromiseLike< T > >
|
PromiseLike< ConcatArray< T | PromiseLike< T > > >;
export function some< T, R >(
list: SomeArray< T >,
fn: SomePredicate< T, R >
)
: SomeReturn< R >;
export function some< T, R >( fn: SomePredicate< T, R > )
: ( list: SomeArray< T > ) => SomeReturn< R >;
export function some< T, R >(
list: SomeArray< T > | SomePredicate< T, R >,
fn?: SomePredicate< T, R >
)
:
SomeReturn< R >
|
( ( list: SomeArray< T > ) => SomeReturn< R > )
{
if ( typeof list === "function" )
{
fn = list;
return ( list: SomeArray< T > ) =>
someImpl( list, < SomePredicate< T, R > >fn );
}
return someImpl( list, < SomePredicate< T, R > >fn );
}
async function someImpl< T, R >(
list: SomeArray< T >,
fn: SomePredicate< T, R >
)
: Promise< R | false >
{
const _list = toReadonlyArray( await list );
for ( const val of _list )
{
const ret = await fn( await val );
if ( ret )
return ret;
}
return false;
}
export type OnceRunnee< T, R > =
T extends void ? ( ( ) => R ) : ( ( t: T ) => R );
export interface OnceRunner
{
< T, R >( fn: OnceRunnee< T, R >, t: T ): R;
< R >( fn: OnceRunnee< void, R > ): R;
}
export function once( ): OnceRunner;
export function once< R >( fn: OnceRunnee< void, R > ): OnceRunnee< void, R >;
export function once< T, R >( fn: OnceRunnee< T, R > ): OnceRunnee< T, R >;
export function once< T, R >( fn?: OnceRunnee< T, R > )
: OnceRunner | OnceRunnee< T, R >
{
if ( fn )
{
const _once = onceDynamic( );
return ( ( t: T ) => _once( fn, t ) ) as OnceRunnee< T, R >;
}
else
return onceDynamic( );
}
interface OnceState< T >
{
hasRun: boolean;
returnValue?: T;
deferred?: EmptyDeferred | Deferred< T >;
}
function onceDynamic( ): OnceRunner
{
const state = new WeakMap< any, OnceState< any > >( );
const ensureState = ( fn: any ) =>
{
if ( !state.has( fn ) )
state.set( fn, { hasRun: false } );
};
return ( < T, R >( fn: OnceRunnee< T, R >, t: T ) =>
{
ensureState( fn );
const stateObject = < OnceState< R > >state.get( fn );
if ( stateObject.hasRun )
{
if ( stateObject.deferred )
return stateObject.deferred.promise;
return stateObject.returnValue;
}
stateObject.hasRun = true;
const ret = fn( t );
const pret = < Promise< T > >< any >ret;
if ( pret !== undefined && pret && typeof pret.then === "function" )
{
stateObject.deferred = defer( void 0 );
return < any >pret
.then(
stateObject.deferred.resolve,
rethrow( stateObject.deferred.reject )
)
.then( ( ) =>
( < Deferred< R > >stateObject.deferred ).promise
);
}
stateObject.returnValue = ret;
return ret;
} ) as OnceRunner;
}
export function retry< R >(
times: number,
fn: ( ) => R,
retryable: ( err: unknown ) => boolean = ( ) => true
)
: R
{
type I = PromiseElement< R >;
const retryAsync = ( promise: Promise< I > ): Promise< I > =>
promise
.catch( ( err: Error ) =>
{
if ( --times < 0 || !retryable( err ) )
throw err;
return retryAsync( < any >fn( ) );
} );
const retrySync = ( _err: unknown ): R =>
{
while ( --times >= 0 )
{
try
{
return < R >fn( );
}
catch ( err )
{
if ( !retryable( err ) )
throw err;
_err = err;
}
}
throw _err;
};
try
{
const ret = fn( );
if (
ret &&
typeof ret === "object" &&
typeof ( < any >ret ).then === "function"
)
{
return < any >retryAsync( < any >ret );
}
return < R >ret;
}
catch ( err )
{
if ( !retryable( err ) )
throw err;
return retrySync( err );
}
}
export interface Deferred< T >
{
resolve: ( t: T | PromiseLike< T > ) => void;
reject: < E extends Error >( err: E ) => void;
promise: Promise< T >;
}
export interface EmptyDeferred
{
resolve: ( ( t: void | PromiseLike< void > ) => void ) & ( ( ) => void );
reject: < E extends Error >( err: E ) => void;
promise: Promise< void >;
}
/**
* Creates a defer object used to pass around a promise and its resolver
*/
export function defer< T >( ): Deferred< T >;
export function defer( v: void ): EmptyDeferred;
export function defer< T = void >( ): Deferred< T >
{
const deferred = < Deferred< T > >{ };
deferred.promise = new Promise< T >( ( resolve, reject ) =>
{
deferred.resolve = resolve;
deferred.reject = reject;
} );
/* istanbul ignore next */
if ( process?.env?.JEST_WORKER_ID !== undefined )
try
{
// Jest has decided for many versions to break async catching,
// so this is needed for unit tests not to break unnecessarily.
deferred.promise.catch( ( ) => { } );
} catch ( _err ) { }
return deferred;
}
export interface ResolvedReflection< T >
{
error?: undefined;
value: T;
isResolved: true;
isRejected: false;
}
export interface RejectedReflection
{
error: Error;
value?: undefined;
isResolved: false;
isRejected: true;
}
export type Reflection< T > = ResolvedReflection< T > | RejectedReflection;
export function reflect< T >( promise: Promise< T > )
: Promise< Reflection< T > >
{
const inspection = inspect( promise );
function handleResolution( value: T ): ResolvedReflection< T >
{
return {
isRejected: false,
isResolved: true,
value,
};
}
function handleRejection( error: Error ): RejectedReflection
{
return {
error,
isRejected: true,
isResolved: false,
};
}
return inspection.promise
.then( handleResolution, handleRejection );
}
export interface InspectablePromise< T >
{
promise: Promise< T >;
isResolved: boolean;
isRejected: boolean;
isPending: boolean;
}
export function inspect< T >( promise: Promise< T > ): InspectablePromise< T >
{
const inspectable: InspectablePromise< T > = {
isPending: true,
isRejected: false,
isResolved: false,
promise: < any >void 0,
};
inspectable.promise = promise.then( value =>
{
inspectable.isResolved = true;
inspectable.isPending = false;
return value;
} )
.catch( err =>
{
inspectable.isRejected = true;
inspectable.isPending = false;
return Promise.reject( err );
} );
return inspectable;
}