-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
1185 lines (1044 loc) · 34 KB
/
mod.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
/**
* Better Iterators
* ================
*
* This module provides {@link Lazy} and {@link LazyAsync} classes which make it easy
* to chain together data transformations.
*
* The {@link lazy} function is the simplest way to get started.
*
* ```ts
* import { lazy, range } from "./mod.ts"
*
* // You can use any Iterable here (such as an Array, or Generator), but
* // Lazy objects are themselves Iterable:
* let iterable = range({to: 1000})
*
* let results = lazy(iterable)
* .filter(it => it % 2 == 0)
* .map(it => it*it)
* .limit(10)
*
* // No iteration has happened yet.
* // This will trigger it:
* for (let item of results) { console.log(item) }
* ```
*
* Lazy Iteration Consumes All Input
* ---------------------------------
*
* Note that iterating a Lazy(Async) will consume its items -- the operation is
* not repeatable. If you need to iterate multiple times, save your result to
* an array with {@link Lazy#toArray}
*
* ```ts
* import { lazy, range } from "./mod.ts"
*
* let results = lazy([1, 2, 3, 4, 5]).map(it => `number: ${it}`)
*
* for (let result of results) { console.log("first pass:", result)}
*
* // Has no more values to yield, will throw an exception:
* for (let result of results) { console.log("second pass:", result)}
* ```
*
* Asynchronous Iteration With Promises (Not Recommended)
* ------------------------------------------------------
*
* Other iterator libraries show examples of parallel/async iteration like this:
*
* ```ts
* import { lazy, range } from "./mod.ts"
* let urls = [
* "https://www.example.com/foo",
* "https://www.example.com/bar"
* ]
* let lazySizes = lazy(urls)
* .map(async (url) => {
* let response = await fetch(url)
* return await response.text()
* })
* // The type is now Lazy<Promise<string>> so we're stuck having to deal
* // with promises for the rest of the lazy chain:
* .map(async (bodyPromise) => (await bodyPromise).length)
* // and so on...
*
* // `lazySizes` also ends up as a `Lazy<Promise<number>>`, so we've got to
* // await all of the items ourselves:
* let sizes = await Promise.all(lazySizes.toArray())
* ```
*
* This approach might seem to work, but it has unbounded parallelism. If you
* have N URLs, `.toArray()` will create N promises, and the JavaScript runtime
* will start making progress on all of them simultaneously.
*
* That might work for small workloads, but network and memory resources are not
* unbounded, so you may end up with worse, or less reliable performance.
*
*
* Lazy Asynchronous Iteration
* ---------------------------
*
* Better Iterators provides a simpler, safer API when working with async code:
* You can convert a `Lazy` to a `LazyAsync`:
*
* ```ts
* import { lazy } from "./mod.ts"
* let urls = [
* "https://www.example.com/foo",
* "https://www.example.com/bar"
* ]
* let lazySizes = lazy(urls)
* .toAsync()
* .map(async (url) => {
* let response = await fetch(url)
* return await response.text()
* })
* // here the type is LazyAsync<string> (not Lazy<Promise<string>>)
* // so further lazy functions are easier to work with:
* .map(it => it.length)
* ```
*
* Here, {@link LazyAsync#map} does the least surprising thing and does not
* introduce parallelism implicitly. You've still got serial lazy iteration.
*
* If you DO want parallelism, you can explicitly opt in like this:
*
* ```ts
* import { lazy } from "./mod.ts"
* let urls = [
* "https://www.example.com/foo",
* "https://www.example.com/bar"
* ]
* let lazySizes = lazy(urls)
* .map({
* parallel: 5,
* async mapper(url) {
* let response = await fetch(url)
* return await response.text()
* }
* })
* // etc.
* ```
*
* Functional Idioms
* -----------------
*
* You'll find other common Functional Programming idioms on the {@link Lazy}
* and {@link LazyAsync} types, like `associateBy`, `groupBy`, `fold`, `sum`,
* `partition`, etc.
*
* @module
*/
import { Peekable, PeekableAsync } from "./_src/peek.ts";
import { stateful, StatefulPromise } from "./_src/promise.ts";
import { Queue } from "./_src/queue.ts";
/**
* Create a Lazy(Async) from your (Async)Iterator.
*/
export function lazy<T>(iter: Iterable<T>): Lazy<T>
export function lazy<T>(iter: AsyncIterable<T>): LazyAsync<T>
export function lazy<T>(iter: Iterable<T>|AsyncIterable<T>): Lazy<T>|LazyAsync<T> {
if (Symbol.asyncIterator in iter) {
return LazyAsync.from(iter)
}
return Lazy.from(iter)
}
// Note: There seems to be a bug in `deno doc` so I'm going to copy/paste the
// method docs onto the implementors. 😢
// https://github.com/denoland/deno_doc/issues/136
/**
* Shared interface for {@link Lazy} and {@link LazyAsync}.
* (Note: `LazyAsync` implements some methods that are not shared.)
*
* You shouldn't need to interact with these classes or this interface
* directly, though. You can use {@link lazy} to automatically instantiate the
* correct one.
*
* Operations on lazy iterators consume the underlying iterator. You should not
* use them again.
*/
export interface LazyShared<T> {
/**
* Apply `transform` to each element.
*
* Works like {@link Array#map}.
*/
map<Out>(transform: Transform<T, Out>): LazyShared<Out>
/**
* Asynchronously transform elements in parallel.
*/
map<Out>(options: ParallelMapOptions<T, Out>): LazyAsync<Out>
/** Keeps only items for which `f` is `true`. */
filter(f: Filter<T>): LazyShared<T>
/** Overload to support type narrowing. */
filter<S extends T>(f: (t: T) => t is S): LazyShared<S>
/** Limit the iterator to returning at most `count` items. */
limit(count: number): LazyShared<T>
/** Collect all items into an array. */
toArray(): Awaitable<Array<T>>
/** Injects a function to run on each T as it is being iterated. */
also(fn: (t: T) => void): LazyShared<T>
/** Partition items into `matches` and `others` according to Filter `f`. */
partition(f: Filter<T>): Awaitable<Partitioned<T>>
/** Get the first item. @throws if there are no items. */
first(): Awaitable<T>
/** Get the first item. Returns `defaultValue` if there is no first item. */
firstOr<D>(defaultValue: D): Awaitable<T|D>
/** Skip (up to) the first `count` elements */
skip(count: number): LazyShared<T>
/**
* Given `keyFn`, use it to extract a key from each item, and create a Map
* grouping items by that key.
*/
groupBy<Key>(keyFn: Transform<T, Key>): Awaitable<Map<Key, T[]>>
/**
* Adds a `valueFn` to extract that value (instead of T) into a group.
*/
groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn: Transform<T, Value>): Awaitable<Map<Key, Value[]>>
/**
* Given `uniqueKeyFn`, use it to extract a key from each item, and create a
* 1:1 map from that to each item.
*
* @throws if duplicates are found for a given key.
*/
associateBy<Key>(
uniqueKeyFn: Transform<T, Key>,
): Awaitable<Map<Key, T>>
/**
* Takes an additional `valueFn` to extract a value from `T`. The returned
* map maps from Key to Value. (instead of Key to T)
*/
associateBy<Key, Value>(
uniqueKeyFn: Transform<T, Key>,
valueFn: Transform<T, Value>
): Awaitable<Map<Key, Value>>
/** Flattens a Lazy<Iterable<T>> to a Lazy<T> */
flatten(): LazyShared<Flattened<T>>
/** Joins multiple string values into a string. */
joinToString(args?: JoinToStringArgs): Awaitable<JoinedToString<T>>
/** Fold values. See example in {@link LazyShared#sum} */
fold<I>(initialValue: I, foldFn: (i: I, t: T) => I): Awaitable<I>
/**
* Sums a Lazy iterator of `number`s.
*
* This is equivalent to:
* ```ts
* import { lazy, range } from "./mod.ts"
*
* range({to: 10}).fold(0, (a, b) => a + b)
* ```
*
*/
sum(): Awaitable<T extends number ? number : never>
// Note: Technically, the sum() implementation will convert non-numbers to
// a string and then do string concatenation. But it's probably not desired,
// and would be more efficient with join(), so we return a `never` type here.
/**
* Averages numbers from the Lazy iterable.
*
* Will return NaN if no numbers exist.
*
* Note: This algorithm does a simple left-to-right accumulation of the sum,
* so can suffer from loss of precision when summing things with vastly
* different scales, or working with sums over Number.MAX_SAFE_INTEGER.
*/
avg(): Awaitable<T extends number ? number : never>
/**
* Get a "peekable" iterator, which lets you peek() at the next item without
* removing it from the iterator.
*/
peekable(): Peekable<T> | PeekableAsync<T>
/**
* Iterate by chunks of a given size formed from the underlying Iterator.
*
* Each chunk will be exactly `size` until the last chunk, which may be
* from 1-size items long.
*/
chunked(size: number): LazyShared<T[]>
/**
* Repeat items `count` times.
*
* ```ts
* import { range } from "./mod.ts"
*
* let nine = range({to: 3}).repeat(3).sum()
* ```
*/
repeat(count: number): LazyShared<T>
/**
* Like {@link #repeat}, but repeates forever.
*/
loop(): LazyShared<T>
}
/**
* Passing this to the map() function indicates that you want to map
* values
*/
export interface ParallelMapOptions<T, Out> {
/**
* The maximum number of map functions to run in parallel.
* This gives you bounded parallelism so that you don't overwhelm
* whatever resource you're mapping with. (ex: fetch, exec, write, etc.)
*/
parallel: number
/**
* The async mapping function to run in parallel.
*/
mapper: (t: T) => Promise<Out>
/**
* Should we maintain the input ordering in the output?
*
* This is the least-surprising behavior, but it comes at the cost of
* potential head-of-line blocking.
*
* Default: true
*/
ordered?: boolean
}
export class Lazy<T> implements Iterable<T>, LazyShared<T> {
/** Prefer to use the {@link lazy} function. */
static from<T>(iter: Iterable<T>): Lazy<T> {
return new Lazy(iter)
}
private constructor(iter: Iterable<T>) {
this.#innerStore = iter
}
#innerStore?: Iterable<T>
get #inner(): Iterable<T> {
let inner = this.#innerStore
this.#innerStore = undefined
if (inner === undefined) {
throw new Error(`Logic Error: Iteration for this Lazy has already been consumed`)
}
return inner
}
[Symbol.iterator](): Iterator<T> {
return this.#inner[Symbol.iterator]()
}
/**
* Apply `transform` to each element.
*
* Works like {@link Array#map}.
*/
map<Out>(transform: Transform<T, Out>): Lazy<Out>;
map<Out>(options: ParallelMapOptions<T,Out>): LazyAsync<Out>;
map<Out>(arg: Transform<T,Out>|ParallelMapOptions<T,Out>): Lazy<Out>|LazyAsync<Out> {
if ("parallel" in arg) {
return this.toAsync().map(arg)
}
return this.#simpleMap(arg)
}
#simpleMap<Out>(transform: Transform<T, Out>): Lazy<Out> {
let inner = this.#inner
let transformIter = function*() {
for (let item of inner) {
yield transform(item)
}
}
return Lazy.from(transformIter())
}
/** Overload to support type narrowing. */
filter<S extends T>(f: (t: T) => t is S): Lazy<S>
/** Keeps only items for which `f` is `true`. */
filter(f: Filter<T>): Lazy<T>
filter(f: Filter<T>): Lazy<T> {
let inner = this.#inner
let matchIter = function*() {
for (let item of inner) {
if (!f(item)) { continue }
yield item
}
}
return Lazy.from(matchIter())
}
/** Limit the iterator to returning at most `count` items. */
limit(count: number): Lazy<T> {
let inner = this.#inner
let countIter = function*() {
if (count <= 0) { return }
for (let item of inner) {
yield item
if (--count <= 0) { break }
}
}
return Lazy.from(countIter())
}
/** Injects a function to run on each T as it is being iterated. */
also(fn: (t: T) => void): Lazy<T> {
let inner = this.#inner
let gen = function*() {
for (let item of inner) {
fn(item)
yield item
}
}
return Lazy.from(gen())
}
/** Partition items into `matches` and `others` according to Filter `f`. */
partition(f: Filter<T>): Partitioned<T> {
let matches: T[] = []
let others: T[] = []
for (const item of this) {
if (f(item)) { matches.push(item) }
else { others.push(item) }
}
return {matches, others}
}
/** Get the first item. @throws if there are no items. */
first(): T {
for (let item of this) {
return item
}
throw new Error(`No items.`)
}
/** Get the first item. Returns `defaultValue` if there is no first item. */
firstOr<D>(defaultValue: D): T | D {
for (let item of this) {
return item
}
return defaultValue
}
/** Skip (up to) the first `count` elements */
skip(count: number): Lazy<T> {
let inner = this.#inner
let gen = function * () {
let iter = inner[Symbol.iterator]()
while (count-- > 0) {
let next = iter.next()
if (next.done) { return }
}
while (true) {
let next = iter.next()
if (next.done) { return }
yield next.value
}
}
return Lazy.from(gen())
}
/**
* Given `keyFn`, use it to extract a key from each item, and create a Map
* grouping items by that key.
*/
groupBy<Key>(keyFn: Transform<T, Key>): Map<Key, T[]>;
/**
* Adds a `valueFn` to extract that value (instead of T) into a group.
*/
groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn: Transform<T, Value>): Map<Key, Value[]>
groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn?: Transform<T, Value|T>): Map<Key, (T|Value)[]> {
let map = new Map<Key, (T|Value)[]>()
valueFn ??= (t) => t
for (const item of this) {
const key = keyFn(item)
let group = map.get(key)
if (!group) {
group = []
map.set(key, group)
}
group.push(valueFn(item))
}
return map
}
/**
* Given `uniqueKeyFn`, use it to extract a key from each item, and create a
* 1:1 map from that to each item.
*
* @throws if duplicates are found for a given key.
*/
associateBy<Key>(uniqueKeyFn: Transform<T, Key>, ): Map<Key, T>;
/**
* Takes an additional `valueFn` to extract a value from `T`. The returned
* map maps from Key to Value. (instead of Key to T)
*/
associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn: Transform<T, Value> ): Map<Key, Value>;
associateBy<Key, Value>(
uniqueKeyFn: Transform<T, Key>,
valueFn?: Transform<T, Value|T>
): Map<Key, T|Value> {
let map = new Map<Key, T|Value>()
valueFn ??= (t) => t
for (const item of this) {
const key = uniqueKeyFn(item)
if (map.has(key)) {
throw new Error(`unique key collision on ${key}`)
}
map.set(key, valueFn(item))
}
return map
}
/** Flattens a Lazy<Iterable<T>> to a Lazy<T> */
flatten(): Lazy<Flattened<T>> {
let inner = this.#inner
return Lazy.from(function * () {
for (const value of inner) {
yield * requireIterable(value)
}
}())
}
/** Joins multiple string values into a string. */
joinToString(args?: JoinToStringArgs): JoinedToString<T> {
const sep = args?.sep ?? ", "
return this.toArray().join(sep) as JoinedToString<T>
}
/** Collect all items into an array. */
toArray(): Array<T> {
return [... this.#inner]
}
/**
* Convert to a LazyAsync, which better handles chains of Promises.
*/
toAsync(): LazyAsync<T> {
let inner = this.#inner
let gen = async function*() {
for (let item of inner) {
yield item
}
}
return LazyAsync.from(gen())
}
fold<I>(initial: I, foldFn: (i: I, t: T) => I): I {
let inner = this.#inner
let accumulator = initial
for (let item of inner) {
accumulator = foldFn(accumulator, item)
}
return accumulator
}
sum(): T extends number ? number : never {
let out = this.fold(0, (a, b) => a + (b as number))
return out as (T extends number ? number : never)
}
avg(): T extends number ? number : never {
let count = 0
let sum = this.also( () => { count += 1 } ).sum()
return sum / count as (T extends number ? number : never)
}
/**
* Get a "peekable" iterator, which lets you peek() at the next item without
* removing it from the iterator.
*/
peekable(): Peekable<T> {
let inner = this.#inner
return Peekable.from(inner)
}
/**
* Iterate by chunks of a given size formed from the underlying Iterator.
*
* Each chunk will be exactly `size` until the last chunk, which may be
* from 1-size items long.
*/
chunked(size: number): Lazy<T[]> {
let inner = this.#inner
let gen = function* generator() {
let out: T[] = []
for (const item of inner) {
out.push(item)
if (out.length >= size) {
yield out
out = []
}
}
if (out.length > 0) {
yield out
}
}
return lazy(gen())
}
/**
* Repeat items `count` times.
*
* ```ts
* import { range } from "./mod.ts"
*
* let nine = range({to: 3}).repeat(3).sum()
* ```
*/
repeat(count: number): Lazy<T> {
if (count < 0) {
throw new Error(`count may not be < 0. Was: ${count}`)
}
if (count == 1) {
return this
}
let inner = this.#inner
const gen = function* generator() {
const arr: T[] = []
for (const item of inner) {
yield item
arr.push(item)
}
if (arr.length == 0) {
return
}
for (let i = 1; i < count; i++) {
yield * arr
}
}
return lazy(gen())
}
/**
* Like {@link #repeat}, but repeates forever.
*/
loop(): Lazy<T> {
let inner = this.#inner
const gen = function* generator() {
const arr: T[] = []
for (const item of inner) {
yield item
arr.push(item)
}
if (arr.length == 0) {
return
}
while (true) {
yield * arr
}
}
return lazy(gen())
}
}
export class LazyAsync<T> implements AsyncIterable<T>, LazyShared<T> {
/**
* This lets you directly create an AsyncIterable, but you might prefer
* the shorter {@link lazy} function.
*/
static from<T>(iter: AsyncIterable<T>): LazyAsync<T> {
return new LazyAsync(iter)
}
private constructor(iter: AsyncIterable<T>) {
this.#innerStore = iter
}
#innerStore?: AsyncIterable<T>
get #inner(): AsyncIterable<T> {
let inner = this.#innerStore
this.#innerStore = undefined
if (inner === undefined) {
throw new Error(`Logic Error: Iteration for this LazyAsync has already been consumed`)
}
return inner
}
[Symbol.asyncIterator](): AsyncIterator<T> {
return this.#inner[Symbol.asyncIterator]()
}
/**
* Apply `transform` to each element.
*
* Works like {@link Array#map}.
*/
map<Out>(transform: Transform<T, Awaitable<Out>>): LazyAsync<Out>;
map<Out>(options: ParallelMapOptions<T, Out>): LazyAsync<Out>;
map<Out>(arg: Transform<T, Awaitable<Out>>|ParallelMapOptions<T,Out>): LazyAsync<Out> {
if ("parallel" in arg) {
const { ordered, parallel, mapper } = arg
if (ordered == false) {
return this.#mapParUnordered(parallel, mapper)
}
return this.#mapPar(parallel, mapper)
}
return this.#simpleMap(arg)
}
#simpleMap<Out>(transform: Transform<T, Awaitable<Out>>): LazyAsync<Out> {
let inner = this.#inner
let gen = async function*() {
for await (let item of inner) {
yield await transform(item)
}
}
return LazyAsync.from(gen())
}
/**
* @deprecated Use {@link map} with {@link ParallelMapOptions} instead.
*/
mapPar<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> {
return this.#mapPar(max, transform)
}
#mapPar<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> {
let inner = this.#inner
let gen = async function*() {
let pending = new Queue<Promise<Out>>()
for await (let item of inner) {
pending.push(transform(item))
while (pending.size >= max) {
yield await pending.pop()
}
}
while (!pending.isEmpty) {
yield await pending.pop()
}
}
return LazyAsync.from(gen())
}
/**
* @deprecated Use {@link map} with {@link ParallelMapOptions}
* and `ordered: false`
*/
mapParUnordered<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> {
return this.#mapParUnordered(max, transform)
}
#mapParUnordered<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> {
if (max <= 0) { throw new Error("max must be > 0")}
let inner = this.#inner
let gen = async function*() {
let pending: StatefulPromise<Out>[] = []
let done: StatefulPromise<Out>[] = []
// Get a list of (at least one) "done" task.
let repartition = async () => {
if (pending.length == 0 || done.length > 0) {
// nothing to do.
return
}
await Promise.race(pending)
let values = lazy(pending)
.partition(it => it.state === "pending")
pending = values.matches
done = values.others
}
for await (let item of inner) {
pending.push(stateful(transform(item)))
while (pending.length + done.length >= max) {
await repartition()
yield done.pop()!
}
}
while (pending.length + done.length > 0) {
await repartition()
for (let d of done) {
yield d
}
done = []
}
}
return LazyAsync.from(gen())
}
/** Overload to support type narrowing. */
filter<S extends T>(f: (t: T) => t is S): LazyAsync<S>
/** Keeps only items for which `f` is `true`. */
filter(f: Filter<T>): LazyAsync<T>
filter(f: Filter<T>): LazyAsync<T> {
let inner = this.#inner
let gen = async function*() {
for await (let item of inner) {
if (f(item)) { yield item }
}
}
return LazyAsync.from(gen())
}
/** Limit the iterator to returning at most `count` items. */
limit(count: number): LazyAsync<T> {
let inner = this.#inner
let countIter = async function*() {
if (count <= 0) { return }
for await (let item of inner) {
yield item
if (--count <= 0) { break }
}
}
return LazyAsync.from(countIter())
}
/** Injects a function to run on each T as it is being iterated. */
also(fn: (t: T) => void): LazyAsync<T> {
let inner = this.#inner
let gen = async function*() {
for await (let item of inner) {
fn(item)
yield item
}
}
return LazyAsync.from(gen())
}
/** Partition items into `matches` and `others` according to Filter `f`. */
async partition(f: Filter<T>): Promise<Partitioned<T>> {
let matches: T[] = []
let others: T[] = []
for await (const item of this) {
if (f(item)) { matches.push(item) }
else { others.push(item) }
}
return {matches, others}
}
/** Get the first item. @throws if there are no items. */
async first(): Promise<T> {
for await (let item of this) {
return item
}
throw new Error(`No items.`)
}
/** Get the first item. Returns `defaultValue` if there is no first item. */
async firstOr<D>(defaultValue: D): Promise<T | D> {
for await (let item of this) {
return item
}
return defaultValue
}
/** Skip (up to) the first `count` elements */
skip(count: number): LazyAsync<T> {
let inner = this.#inner
let gen = async function * () {
let iter = inner[Symbol.asyncIterator]()
while (count-- > 0) {
let next = await iter.next()
if (next.done) { return }
}
while (true) {
let next = await iter.next()
if (next.done) { return }
yield next.value
}
}
return LazyAsync.from(gen())
}
/**
* Given `keyFn`, use it to extract a key from each item, and create a Map
* grouping items by that key.
*/
async groupBy<Key>(keyFn: Transform<T, Key>): Promise<Map<Key, T[]>>
/**
* Adds a `valueFn` to extract that value (instead of T) into a group.
*/
async groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn: Transform<T, Value>): Promise<Map<Key, Value[]>>
async groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn?: Transform<T, Value|T>): Promise<Map<Key, (T|Value)[]>> {
let map = new Map<Key, (T|Value)[]>()
valueFn ??= (t) => t
for await (const item of this) {
const key = keyFn(item)
let group = map.get(key)
if (!group) {
group = []
map.set(key, group)
}
group.push(valueFn(item))
}
return map
}
/**
* Given `uniqueKeyFn`, use it to extract a key from each item, and create a
* 1:1 map from that to each item.
*
* @throws if duplicates are found for a given key.
*/
associateBy<Key>( uniqueKeyFn: Transform<T, Key>, ): Promise<Map<Key, T>>;
/**
* Takes an additional `valueFn` to extract a value from `T`. The returned
* map maps from Key to Value. (instead of Key to T)
*/
associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn: Transform<T, Value> ): Promise<Map<Key, Value>>;
async associateBy<Key, Value>(
uniqueKeyFn: Transform<T, Key>,
valueFn?: Transform<T, T|Value>
): Promise<Map<Key, T|Value>> {
let map = new Map<Key, T|Value>()
valueFn ??= (t) => t
for await (const item of this) {
const key = uniqueKeyFn(item)
if (map.has(key)) {
throw new Error(`unique key collision on ${key}`)
}
map.set(key, valueFn(item))
}
return map
}
/** Flattens a Lazy<Iterable<T>> to a Lazy<T> */
flatten(): LazyAsync<Flattened<T>> {
let inner = this.#inner
return LazyAsync.from(async function * () {
for await (const value of inner) {
yield * requireIterable(value)
}
}())
}
/** Joins multiple string values into a string. */
async joinToString(args?: JoinToStringArgs): Promise<JoinedToString<T>> {
const sep = args?.sep ?? ", "
return (await this.toArray()).join(sep) as JoinedToString<T>
}
/** Collect all items into an array. */
async toArray(): Promise<T[]> {
let out: T[] = []
for await (let item of this) {
out.push(item)
}
return out
}
async fold<I>(initial: I, foldFn: (i: I, t: T) => I): Promise<I> {
let inner = this.#inner
let accumulator = initial
for await (let item of inner) {
accumulator = foldFn(accumulator, item)
}
return accumulator
}
async sum(): Promise<T extends number ? number : never> {
let out = await this.fold(0, (a, b) => a + (b as number))
return out as (T extends number ? number : never)
}
async avg(): Promise<T extends number ? number : never> {
let count = 0
let sum = await this.also( () => { count += 1 } ).sum()
return sum / count as (T extends number ? number : never)
}
/**
* Get a "peekable" iterator, which lets you peek() at the next item without
* removing it from the iterator.
*/
peekable(): PeekableAsync<T> {
let inner = this.#inner
return PeekableAsync.from(inner)
}