-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
896 lines (836 loc) · 24.8 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
import { Option, some } from "./option.ts";
import { ok, Result } from "./result.ts";
import { Collection, Constructor, default as extend } from "./extender.ts";
/**
* **Comparator** represents a comparator functions.
* If the return value is positive, lhs is greater than rhs.
* If it's negative, then lhs is less than rhs.
* Else lhs and rhs are equal.
*/
type Comparator<T, U> = (lhs: T, rhs: U) => number;
/**
* PartialComparator is the same as Comparator.
* It returns null instead of a number when 2 elements can't
* be compared. Such an example would be comparing NaN to
* a number - this should return null.
*/
type PartialComparator<T, U> = (lhs: T, rhs: U) => Option<number>;
/**
* **maxCmp** is used internally as a comparison function
* for Iter methods **max** and **maxByKey**. As **maxBy**
* only swaps values if the return value of the function is
* positive (lhs is greater), this function ignores the case
* when lhs is less than rhs. Because of this, it is a malformed
* comparator otherwise, so it should not be used in any other
* context.
*/
const maxCmp = <T>(lhs: T, rhs: T): number => {
if (lhs > rhs) {
return 1;
}
return 0;
};
/**
* **minCmp** is the same as **maxCmp**, but returns -1 if lhs
* is less than rhs.
*/
const minCmp = <T>(lhs: T, rhs: T): number => {
if (lhs < rhs) {
return -1;
}
return 0;
};
const fromIntoIter = <T>(i: IntoIter<T>): Iter<T> => {
if (i instanceof Iter) {
return i;
}
return new Iter(i);
};
/**
* **IntoIter** is the type that a value must satisfy to
* be turned into an Iter
*/
export type IntoIter<T> = Iterable<T> | Iterator<T>;
/**
* Iter is a wrapper over ECMAScript 2015's protocol.
* Based on the protocol defined next() method, Iter provides
* various convenience methods for lazy iteration over collections
* that implement the protocol.
*
* In other words, any object that implements either Symbol.iterator
* or a next() method can be wrapped by Iter! An Iter can only be
* used once: multiple calls to Symbol.iterator return the same
* underlying Iterator instance.
*
* @example
* // Simple usage
* const set = new Set();
* set.add("a");
* set.add("b");
* set.add("c");
* set.add("c");
* const iter = new Iter(set);
* for (const [index, elem] of iter.enumerate()) {
* console.log(`${index}: ${elem}`);
* }
*
* @example
* // Process a generator
* function* gen() {
* while (true) {
* yield Math.random();
* }
* }
* const rands = [...new Iter(gen).take(5).map(n => n * 100).map(Math.floor)];
* console.log(rands);
* // possible output: [ 23, 54, 32, 65, 38 ]
*
* @example
* // Iter is consumable
* const iter = new Iter([1, 2, 3, 4]);
* for (const elem of iter) {
* console.log(elem);
* }
* for (const elem of iter) {
* console.log(elem);
* }
* // output:
* // 1
* // 2
* // 3
* // 4
*
* @template T the type to iterate over
*/
export default class Iter<T> implements IterableIterator<T> {
private readonly iter: Iterator<T>;
/**
* Wraps any object that is an iterable or an iterator in
* an Iter object
*
* @param iter The object to wrap
*/
constructor(iter: IntoIter<T>) {
if (Symbol.iterator in iter) {
this.iter = (iter as Iterable<T>)[Symbol.iterator]();
} else {
this.iter = iter as Iterator<T>;
}
}
[Symbol.iterator]() {
return this;
}
/**
* **next** advances the iterator, returning the next element
* and a done flag that indicates if the iteration ended
*
* @example
* const it = new Iter([1, 2, 3]);
* let { value, done } = it.next(); assert(value === 1 && !done);
* ({ value, done } = it.next()); assert(value === 2 && !done);
* ({ value, done } = it.next()); assert(value === 3 && !done);
* ({ value, done } = it.next()); assert(typeof value === "undefined" && done);
*/
next(): IteratorResult<T> {
return this.iter.next();
}
/**
* **enumerate** creates an iterator which gives the current
* iteration count as well as the next value.
* The returned iterator yields tuples of a number and
* a value, where the number is the current index of the
* iteration and the value is the value returned by the
* iterator.
*/
enumerate(): Iter<[number, T]> {
let index = 0;
const next = (): IteratorResult<[number, T]> => {
const { value, done } = this.next();
return { value: [index++, value], done };
};
return new Iter({ next });
}
/**
* **fold** applies a function to each element, returning
* a single value and consuming the iterator.
*
* It is also called **reduce** or **inject**.
*
* @example
* const set = new Set(["doorknob", "cappucino", "cappucino", "pianissimo", "baz", "abdicate"]);
* const word = new Iter(set).fold('', (acc, w) => acc + w.slice(-1));
* assertStrictEquals(word, "booze");
*
* @param init The accumulator's initial value.
* @param f Function that takes as arguments the
* accumulator's value and the current value iterated
* over and returns the new accumulator value.
* @returns the final accumulator value
*/
fold<U>(init: U, f: (acc: U, v: T) => U): U {
for (
let { value, done } = this.next();
!done;
({ value, done } = this.next())
) {
init = f(init, value);
}
return init;
}
/**
* **fold1** is the same as **fold**, but uses the first
* element as the initial value for the accumulator.
* If the iterator is empty, it returns null, else the
* result of the fold
*
* @param f
*/
fold1(f: (acc: T, v: T) => T): Option<T> {
const { value, done } = this.next();
if (done) {
return null;
}
return this.fold(value, f);
}
/**
* **count** counts the elements in the iterator by calling
* **next** repeatedly until the iterator is consumed.
*
* @returns the number of elements in the iterator
*/
count(): number {
return this.fold(0, (acc) => acc + 1);
}
/**
* **forEach** calls the provided function for each element in
* the iterator, consuming it.
*
* @param f The function to call
*/
forEach(f: (value: T) => void): void {
this.fold<void>(undefined, (_, value) => f(value));
}
/**
* @returns the last element in the iterator, if any, consuming
* the iterator.
*/
last(): Option<T> {
return this.fold<Option<T>>(null, (_, v) => v);
}
/**
* **tryFold** applies the function as long as it returns successfully,
* producing a final, single value. Check Result's documentation to see
* how to use it.
*
* This function works the same as **fold**, except that it short-circuits
* when an error occurs. If all the function calls succeed, the final value
* of the accumulator is returned, else the first error that occured is.
*
* @example
* const sum = new Iter(stringArray).tryFold(0, (acc, v) => {
* const num = parseInt(v, 10);
* if (Number.isNaN(num)) {
* return { success: false };
* }
* return { success: true, value: acc + num };
* })
* // see ok documentation
* if (ok(sum)) {
* console.log(sum.value);
* } else {
* console.log("A string was not a number!");
* }
*
* @param init The inital value of the accumulator
* @param f The function to be applied
* @returns The final value of the accumulator, if the function succeeds,
* else the first error that occured
*/
tryFold<U, E>(init: U, f: (acc: U, v: T) => Result<U, E>): Result<U, E> {
for (
let { value: v, done } = this.next();
!done;
({ value: v, done } = this.next())
) {
const res = f(init, v);
if (ok(res)) {
init = res.value;
} else {
return res;
}
}
return { success: true, value: init };
}
/**
* **tryForEach** consumes the iterator, applying the provided function
* to each element. If the function returns unsuccessfully, the iteration
* stops and the error is returned.
*
* @param f The function to call
* @returns nothing, if the calls to the function succeeded on all elements,
* else the first error that occurred.
*/
tryForEach<E>(f: (v: T) => Result<void, E>): Result<void, E> {
return this.tryFold<void, E>(undefined, (_, v) => f(v));
}
/**
* **find** finds the first element in the iterator that satisfies the
* given predicate, consuming all the previous elements.
*
* @param p The predicate to be satisfied
* @returns The first element satisfying the predicate, if any
*/
find(p: (v: T) => boolean): Option<T>;
find<S extends T>(p: (v: T) => v is S): Option<S>;
find(p: (v: T) => boolean): Option<T> {
return this.tryFold<null, T>(null, (_, value) => {
if (p(value)) {
return { success: false, value };
}
return { success: true, value: null };
}).value;
}
/**
* **findMap** finds the first element that after applying the function
* is not null, consuming all the previous elements.
*
* @example
* function coolParseInt(s: string): Option<number> {
* const num = parseInt(s, 10);
* if (Number.isNaN(num)) {
* return null;
* }
* return num;
* }
*
* const arr = ["lol", "NaN", "2", "5"];
* const firstNumber = new Iter(arr).findMap(coolParseInt);
* assertStrictEquals(firstNumber, 2);
*
* @param f The function to apply
* @returns The first non-null value after the function was applied, if any
*/
findMap<U>(f: (v: T) => Option<U>): Option<U> {
return this.tryFold<null, U>(null, (_, v) => {
const value = f(v);
if (some(value)) {
return { success: false, value };
}
return { success: true, value: null };
}).value;
}
/**
* **filter** creates an iterator that returns only the elemnts in the old
* iterator that satisfy the given predicate
*
* @example
* const numbers = [1, 2, 3, 4, 5];
* const coolNumbers = [...new Iter(numbers).filter((n) => n > 2)];
* assertEquals(coolNumbers, [ 3, 4, 5, ]);
*
* @param p The predicate to be satisfied
*/
filter(p: (v: T) => boolean): Iter<T>;
filter<S extends T>(p: (v: T) => v is S): Iter<S>;
filter(p: (v: T) => boolean): Iter<T> {
const next = (): IteratorResult<T> => {
const value = this.find(p);
if (some(value)) {
return { value };
}
return { value, done: true };
};
return new Iter({ next });
}
/**
* **filterMap** creates an iterator that returns only the non-null elements
* resulted from applying the passed function to the elements of the old iterator.
*
* @example
* function coolParseInt(s: string): Option<number> {
* const num = parseInt(s, 10);
* if (Number.isNaN(num)) {
* return null;
* }
* return num;
* }
* const numbers = [...new Iter(["a", "b", "1", "2", "c"]).filterMap(coolParseInt)];
* assertEquals(numbers, [1, 2]);
*
* @param f The function to be applied
*/
filterMap<U>(f: (v: T) => Option<U>): Iter<U> {
const next = (): IteratorResult<U> => {
const value = this.findMap(f);
if (some(value)) {
return { value };
}
return { value, done: true };
};
return new Iter({ next });
}
/**
* **map** creates a new iterator that calls the given function
* on each element of the old iterator.
*
* In other words, it transforms an iterator over elements of type
* T into an iterator over elements of type U, where U is the result
* of the given function
*
* **map** is lazy, meaning that it won't execute until the iterator
* is consumed. If you want to loop over the collection for side effects
* use a for..of construct or Iter's **forEach** method.
*
* @example
* const square = [...new Iter([1, 2, 3, 4]).map((n) => n * n)];
* assertEquals(square, [1, 4, 9, 16]);
*
* @example
* const arr = [1, 2, 3, 4];
* new Iter(arr).map(console.log) // this won't execute
*
* // do this
* for (const elem of arr) {
* console.log(elem);
* }
* // or this
* new Iter(arr).forEach(console.log);
*
* @param f The function to apply
*/
map<U>(f: (v: T) => U): Iter<U> {
const next = (): IteratorResult<U> => {
const { value, done } = this.next();
if (done) {
return { value, done };
}
return { value: f(value) };
};
return new Iter({ next });
}
/**
* **cmpBy** lexicographically compares the elements in this iterator
* to the ones in the other iterator using the given comparator.
*
* The comparator returns a negative number if *lhs* precedes *rhs*, 0
* if they are equal, or a positive number if *lhs* succeeds *rhs*.
*
* This can be used to compare iterators over distinct types.
*
* If you find yourself comparing types that have partial equality only
* (not all values can be compared, such as NaN for numbers), use
* **partialCmpBy** instead.
*
* @param i The iterable or iterator to compare to
* @param cmp The comparison function
*/
cmpBy<U>(
i: IntoIter<U>,
cmp: Comparator<T, U>,
): number {
const other = fromIntoIter(i);
while (true) {
const lhs = this.next();
const rhs = other.next();
if (lhs.done) {
if (rhs.done) {
return 0;
}
return -1;
}
if (rhs.done) {
return 1;
}
const cmpRes = cmp(lhs.value, rhs.value);
if (cmpRes !== 0) {
return cmpRes;
}
}
}
/**
* **cmp** lexicographically compares this iterator to the other.
*
* This function uses strict equality and operators `<` and `>` to compare
* the values. If this doesn't satisfy your requirement, use **cmpBy** with
* your custom comparator.
*/
cmp(i: IntoIter<T>): number {
return this.cmpBy(i, (lhs, rhs) => {
if (lhs < rhs) {
return -1;
}
if (lhs > rhs) {
return 1;
}
return 0;
});
}
/**
* **eqBy** checks if two iterators are equal with the given
* identity function.
*
* This can be used to compare iterators over distinct types,
* if needed.
*
* If you find yourself comparing types that have partial equality only
* (not all values can be compared, such as NaN for numbers), use
* **partialCmpBy** instead.
*
* @param i The iterable or iterator to compare to
* @param eq The identity function
*/
eqBy<U>(i: IntoIter<U>, eq: (lhs: T, rhs: U) => boolean): boolean {
const other = fromIntoIter(i);
while (true) {
const lhs = this.next();
const rhs = other.next();
if (lhs.done) {
return !!rhs.done;
}
if (rhs.done) {
return false;
}
if (!eq(lhs.value, rhs.value)) {
return false;
}
}
}
/**
* **eq** determines if this iterator is equal to another
* using strict equality.
*/
eq(i: IntoIter<T>): boolean {
return this.eqBy(i, (lhs, rhs) => lhs === rhs);
}
/**
* **ne** determines if this iterator is not equal to another
* using strict equality.
*/
ne(i: IntoIter<T>): boolean {
return !this.eq(i);
}
/**
* **ge** determines if the elements of this iterator are
* lexicographically greater or equal than the elements of
* another.
*/
ge(i: IntoIter<T>): boolean {
return this.cmp(i) >= 0;
}
/**
* **gt** determines if the elements of this iterator are
* lexicographically greater than the elements of another.
*/
gt(i: IntoIter<T>): boolean {
return this.cmp(i) > 0;
}
/**
* **le** determines if the elements of this iterator are
* lexicographically lower or equal to the elements of another.
*/
le(i: IntoIter<T>): boolean {
return this.cmp(i) <= 0;
}
/**
* **lt** determines if the elements of this iterator are
* lexicographically lower than the elements of another.
*/
lt(i: IntoIter<T>): boolean {
return this.cmp(i) < 0;
}
/**
* **partialCmpBy** lexicographically compares two iterators using the
* provided comparator.
*
* Use this function if you're comparing values that have only partial
* equality relationship (they can't always be compared, such as NaN
* for numbers). Read further for details.
*
* The difference between **cmpBy** and this function is that this
* should be used when the two types can't always be compared. Take
* floating point numbers, for example: NaN is not equal to any other
* number. If a NaN would exist in an iterator **cmpBy** would simply
* return false, which is not a valid result in this situation.
*
* @example
*
* function cmpNumbers(lhs: nummber, rhs: number): Option<number> {
* if (Number.isNaN(lhs) || Number.isNaN(rhs)) {
* return null;
* }
* return lhs - rhs;
* }
*
* const lhs = [1.0, 2.3, 4.6, 7.8];
* assert(new Iter(lhs).partialCmpBy([1.0, 2.3, 4.6, 7.8], cmpNumbers) === 0);
* assert(new Iter(lhs).partialCmpBy([1.0, 2.2, NaN, 7.8], cmpNumbers) > 0);
* assert(new Iter(lhs).partialCmpBy([1.0, 2.3, NaN, 7.8], cmpNumbers) === null);
*
* @param i The iterable or iterator to compare to.
* @param cmp The comparison function.
*/
partialCmpBy<U>(
i: IntoIter<U>,
cmp: PartialComparator<T, U>,
): Option<number> {
const other = fromIntoIter(i);
while (true) {
const lhs = this.next();
const rhs = other.next();
if (lhs.done) {
if (rhs.done) {
return 0;
}
return -1;
}
if (rhs.done) {
return 1;
}
const cmpRes = cmp(lhs.value, rhs.value);
if (!some(cmpRes) || cmpRes !== 0) {
return cmpRes;
}
}
}
/**
* **all** tests if every element of the iterator satisfies
* the given predicate.
*
* This function short-circuits on first occurence of false,
* which means the rest of the elements after the first that
* does not satisfy the predicate are still available for
* iteration.
*
* @example
*
* assert(new Iter([1, 2, 3]).all((n) => n > 0));
*
* @example
*
* const iter = new Iter([1, 2, 3]);
* assert(!iter.all((n) => n !== 2));
* assertStrictEquals(iter.next().value, 3);
*
* @param p The predicate to be satisfied
*/
all(p: (v: T) => boolean): boolean {
return this.tryFold(
undefined,
// This assigns false to success when the predicate
// isn't satisfied, which makes tryFold end iteration.
// success will be true if all elements satisfy the
// predicate, else false, so it correctly indicates if all
// elements satisfy the predicate
(_, v) => ({ success: p(v), value: undefined }),
).success;
}
/**
* **any** tests if any element in the iterator satisfies the
* predicate.
*
* This function short-circuits on the first occurrence of true,
* which means the rest of elements after the first element
* that satisfied the predicate are still available for iteration.
*
* @example
*
* assert(new Iter([1, 2, 3]).any((n) => n > 0));
*
* @example
*
* const iter = new Iter([1, 2, 3]);
* assert(iter.any((n) => n !== 2));
* assertStrictEquals(iter.next().value, 2);
*
* @param p The predicate to be satisfied
*/
any(p: (v: T) => boolean): boolean {
return !this.tryFold(
undefined,
// This assigns false to succes when the predicate
// is satisfied, which makes tryFold finish iteration.
// Because success will be false, but false means there
// is an element satisfying the predicate, the return
// value of tryFold is negated above.
(_, v) => ({ success: !p(v), value: undefined }),
).success;
}
/**
* **maxBy** returns the element with the maximum value with
* respect to the specified comparison function
*
* Returns null if the iterator is empty.
*
* @param cmp The comparison function to use
*/
maxBy(cmp: Comparator<T, T>): Option<T> {
return this.fold1((max, v) => {
if (cmp(v, max) > 0) {
return v;
}
return max;
});
}
/**
* **max** returns the maximum element in the iterator, with
* respect to operator `>`.
*
* Returns null if the iterator is empty.
*/
max(): Option<T> {
return this.maxBy(maxCmp);
}
/**
* **maxByKey** return the element that gives the maximum value
* from the specified function.
*
* Returns null if the iterator is empty.
*
* @param f The function to get the value to compare
* @param cmp Optional comparator, if operator `>` doesn't suffice.
*/
maxByKey<U>(f: (v: T) => U, cmp: Comparator<U, U> = maxCmp): Option<T> {
const res = this.map<[U, T]>((v) => [f(v), v]).maxBy(([lhs], [rhs]) =>
cmp(lhs, rhs)
);
if (some(res)) {
return res[1];
}
return null;
}
/**
* **minBy** returns the minimum element in the iterator, with
* respect to the specified comparison function.
*
* Returns null if the iterator is empty.
*
* @param cmp The comparison function
*/
minBy(cmp: Comparator<T, T>): Option<T> {
return this.fold1((min, v) => {
if (cmp(v, min) < 0) {
return v;
}
return min;
});
}
/**
* **min** returns the minimum element in the iterator, with
* respect to operator `<`.
*
* Returns null if the iterator is empty.
*/
min(): Option<T> {
return this.minBy(minCmp);
}
/**
* **minByKey** return the element that gives the minimum value
* from the specified function.
*
* Returns null if the iterator is empty.
*
* @param f The function to get the value to compare
* @param cmp Optional comparator, if operator `<` doesn't suffice.
*/
minByKey<U>(f: (v: T) => U, cmp: Comparator<U, U> = minCmp): Option<T> {
const res = this.map<[U, T]>((v) => [f(v), v]).minBy(([lhs], [rhs]) =>
cmp(lhs, rhs)
);
if (some(res)) {
return res[1];
}
return null;
}
/**
* **zip** 'zips up' two iterators into a single iterator of pairs.
*
* It returns a new iterator that will iterate over two other iterators,
* returning a tuple where the first element comes from the first iterator,
* and the second element comes from the second iterator.
*
* In other words, it zips two iterators together, into a single one.
*
* If either iterator is done before the other, this iterator will be done.
*
* @param other The iterable to zip with
*/
zip<U>(other: IntoIter<U>): Iter<[T, U]> {
const iter = new Iter(other);
const next = (): IteratorResult<[T, U]> => {
const lhs = this.next();
if (lhs.done) {
return { value: undefined, done: true };
}
const rhs = iter.next();
if (rhs.done) {
return { value: undefined, done: true };
}
return { value: [lhs.value, rhs.value] };
};
return new Iter({ next });
}
/**
* **collect** Collects all the Iter's elements into a collection.
*
* It is strongly recommended to use alternative methods
* to do this, such as using the spread operator, if collecting
* into an array, or passing the Iter as a constructor parameter,
* if collecting into a Set or a Map.
*
* This method is useful if you want to join multiple strings into
* one without creating a temporary array.
*
* @param constructor The constructor of the collection.
* @returns The collection with the iterator elements.
*/
collect<
U extends Constructor<T>,
V extends Collection<T, U> = Collection<T, U>,
>(
constructor: U,
): V {
const [collection, extender] = extend<T>(constructor);
return this.fold(collection, extender) as V;
}
/**
* **unzip** Converts an iterator of pairs into a pair of containers.
*
* It consumes an entire iterator of pairs, producing two collections:
* one from the left elements of the pairs, and one from the right elements.
*
* This function is, in some sense, the opposite of zip.
*
* NOTE: The type system tries to prevent calling this method
* if Iter's element type isn't a tuple, and ignoring it will
* result in a thrown exception.
*
* @param ca The constructor of the first collection.
* @param cb The constructor of the second collection.
* @returns A tuple with the resulted collections.
*/
unzip<
A extends Constructor<First<T>>,
B extends Constructor<Second<T>>,
VA extends Collection<First<T>, A> = Collection<First<T>, A>,
VB extends Collection<Second<T>, B> = Collection<Second<T>, B>,
>(
ca: A,
cb: B,
): [VA, VB] {
const [colA, extA] = extend<First<T>>(ca);
const [colB, extB] = extend<Second<T>>(cb);
return this.fold([colA, colB], (acc, v) => {
acc[0] = extA(
acc[0] as typeof colA,
(v as unknown as [First<T>, Second<T>])[0],
);
acc[1] = extB(
acc[1] as typeof colB,
(v as unknown as [First<T>, Second<T>])[1],
);
return acc;
}) as [VA, VB];
}
}
type First<T> = [T] extends [[infer K, unknown]] ? K : never;
type Second<T> = [T] extends [[unknown, infer K]] ? K : never;