forked from mkloubert/node-enumerable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enumerable_1.ts
2826 lines (2619 loc) · 66.5 KB
/
enumerable_1.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
import {
AsyncAction,
CancelableFactory,
Comparer,
EachAction,
EqualityComparer,
IEnumerable,
IGrouping,
IOrderedEnumerable,
ItemMessage,
JoinedItems,
PoppableStack,
Predicate,
Selector,
Sequence,
ShiftableStack,
Stack,
ZipSelector,
} from "./enumerable_define";
const Enumerable: Record<string, any> = {
/**
* Indicates that something is empty.
*/
IS_EMPTY: Symbol("IS_EMPTY"),
/**
* Indicates that something is an enumerable (sequence).
*/
IS_ENUMERABLE: Symbol("IS_ENUMERABLE"),
/**
* Indicates if something was not found.
*/
NOT_FOUND: Symbol("NOT_FOUND"),
};
/**
* Represents a list of errors.
*/
class AggregateError extends Error {
/**
* Stores the errors.
*/
protected _errors: any[];
/**
* Initializes a new instance of that class.
*
* @param {any[]} [errors] The occurred errors.
*/
constructor(errors?: any[]) {
super();
this._errors = (errors || []).filter((e) => {
return !isNullOrUndefined(e);
});
}
/**
* Gets the errors.
*/
public get errors() {
return this._errors;
}
/** @inheritdoc */
public get stack() {
return this.errors
.map((e, i) => {
const TITLE = "STACK #" + (i + 1);
const LINE = repeat("=", TITLE.length + 5).joinToString();
return `${TITLE}\n${LINE}\n${toStringSafe(e["stack"])}`;
})
.join("\n\n");
}
/** @inheritdoc */
public toString() {
return this.errors
.map((e, i) => {
const TITLE = "ERROR #" + (i + 1);
const LINE = repeat("=", TITLE.length + 5).joinToString();
return `${TITLE}\n${LINE}\n${e}`;
})
.join("\n\n");
}
}
Enumerable.AggregateError = AggregateError;
/**
* A error wrapper for a function.
*/
class FunctionError extends Error {
/**
* Stores the inner error.
*/
protected _error: any;
/**
* Stores the underlying function.
*/
protected _function: Function;
/**
* Stores the (zero based) index.
*/
protected _index: number;
/**
* Initializes a new instance of that class.
*
* @param {any} [err] The underlying, inner error.
* @param {Function} [func] The underlying function.
* @param {number} [index] The (zero based) index.
*/
constructor(err?: any, func?: Function, index?: number) {
super();
this._error = err;
this._function = func;
this._index = index;
}
/**
* Gets the (zero based) index.
*/
public get index() {
return this._index;
}
/**
* Gets the inner error.
*/
public get innerError() {
return this._error;
}
/** @inheritdoc */
public get stack() {
if (this.innerError) {
return this.innerError["stack"];
}
}
/** @inheritdoc */
public toString() {
let title = "ACTION ERROR";
if (!isNaN(this.index)) {
title += " #" + this.index;
}
const LINE = repeat("=", title.length + 5).joinToString();
let content = "";
if (this.innerError) {
content += this.innerError;
}
return `${title}\n${LINE}\n${content}`;
}
}
Enumerable.FunctionError = FunctionError;
/**
* A basic sequence.
*/
abstract class EnumerableBase<T> implements IEnumerable<T> {
/**
* Stores the current iterator result.
*/
protected _current: IteratorResult<T>;
/**
* Stores the current index.
*/
protected _index: number;
/**
* Indicates that that instance is an enumerable (sequence).
*/
readonly IS_ENUMERABLE: symbol;
constructor() {
/**
* Stores the current index.
*/
this._index = -1;
/**
* Indicates that that instance is an enumerable (sequence).
*/
this.IS_ENUMERABLE = Enumerable.IS_ENUMERABLE;
}
/** @inheritdoc */
[Symbol.iterator]() {
return this;
}
abstract next(...args: []): IteratorResult<T>;
/** @inheritdoc */
public abs(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) => {
return invokeForValidNumber(x, (y) => Math.abs(y), handleAsInt);
});
}
/** @inheritdoc */
public aggregate<TAccumulate = T, TResult = T>(
func: (accumulator: TAccumulate, item: T) => TAccumulate,
seed?: TAccumulate,
resultSelector?: (accumulator: TAccumulate) => TResult,
): TResult {
// if (!func) {
// func = (acc, item) => acc + item;
// }
const _func = !func ? (acc: any, item: any) => acc + item : func;
if (!resultSelector) {
resultSelector = (acc) => acc as unknown as TResult;
}
let acc = seed;
for (let item of this) {
acc = _func(acc, item);
}
return resultSelector(acc);
}
/** @inheritdoc */
public all(predicate: Predicate<T>): boolean {
const _predicate = toPredicateSafe(predicate);
for (let item of this) {
if (!_predicate(item)) {
return false;
}
}
return true;
}
/** @inheritdoc */
public any(predicate: Predicate<T>): boolean {
const _predicate = toPredicateSafe(predicate);
for (let item of this) {
if (_predicate(item)) {
return true;
}
}
return false;
}
/** @inheritdoc */
public append<U = T>(...args: Sequence<U>[]): IEnumerable<T | U> {
return this.concat.apply(this, arguments);
}
/** @inheritdoc */
public appendArray<U = T>(
sequences: ArrayLike<Sequence<U>>,
): IEnumerable<T | U> {
return this.concatArray.apply(this, arguments);
}
/** @inheritdoc */
public arcCos(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.acos(y), handleAsInt),
);
}
/** @inheritdoc */
public arcCosH(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.acosh(y), handleAsInt),
);
}
/** @inheritdoc */
public arcSin(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.asin(y), handleAsInt),
);
}
/** @inheritdoc */
public arcSinH(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.asinh(y), handleAsInt),
);
}
/** @inheritdoc */
public arcTan(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.atan(y), handleAsInt),
);
}
/** @inheritdoc */
public arcTanH(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.atanh(y), handleAsInt),
);
}
/** @inheritdoc */
public assert(predicate: Predicate<T>, errMsg?: ItemMessage<T>): this {
const _predicate = toPredicateSafe(predicate);
errMsg = toItemMessageSafe(errMsg);
let i = -1;
for (let item of this) {
++i;
if (!_predicate(item)) {
throw errMsg(item, i);
}
}
return this;
}
/** @inheritdoc */
public assertAll(predicate: Predicate<T>, errMsg?: ItemMessage<T>): this {
predicate = toPredicateSafe(predicate);
errMsg = toItemMessageSafe(errMsg);
const ERRORS = [];
let i = -1;
for (let item of this) {
++i;
if (!predicate(item)) {
ERRORS.push(errMsg(item, i));
}
}
if (ERRORS.length > 0) {
throw new AggregateError(ERRORS);
}
return this;
}
/** @inheritdoc */
public async(action: AsyncAction<T>, previousValue?: any): Promise<any> {
const ME = this;
return new Promise((resolve, reject) => {
let asyncResult: any;
const ASYNC_COMPLETED = (err: any) => {
if (err) {
reject(err);
} else {
resolve(asyncResult);
}
};
try {
let i = -1;
let prevVal = previousValue;
let val: any;
const NEXT_ITEM = () => {
++i;
const ITEM = this.next();
if (!ITEM || ITEM.done) {
ASYNC_COMPLETED(null);
return;
}
const CTX: any = {
cancel: function (result: any) {
if (arguments.length > 0) {
asyncResult = result;
}
ASYNC_COMPLETED(null);
},
index: i,
isFirst: 0 === i,
item: ITEM.value,
previousValue: prevVal,
reject: function (reason: any, result?: any) {
if (arguments.length > 1) {
asyncResult = result;
}
ASYNC_COMPLETED(reason);
},
resolve: function (nextValue?: any) {
prevVal = nextValue;
NEXT_ITEM();
},
result: undefined,
sequence: ME,
value: undefined,
};
// ctx.result
Object.defineProperty(CTX, "result", {
get: () => {
return asyncResult;
},
set: (newValue) => {
asyncResult = newValue;
},
enumerable: true,
});
// ctx.value
Object.defineProperty(CTX, "value", {
get: () => {
return val;
},
set: (newValue) => {
val = newValue;
},
enumerable: true,
});
try {
if (action) {
action(CTX);
} else {
CTX.resolve();
}
} catch (e) {
CTX.reject(e);
}
};
NEXT_ITEM();
} catch (e) {
ASYNC_COMPLETED(e);
}
});
}
/** @inheritdoc */
public average(selector?: Selector<T, number>): number | symbol {
if (!selector) {
selector = (i) => i as unknown as number;
}
let count = 0;
let sum = 0.0;
for (let n of this.select(selector)) {
if (!isNullOrUndefined(n)) {
if ("number" !== typeof n) {
n = parseFloat(toStringSafe(n).trim());
}
}
++count;
sum += n;
}
return count > 0 ? sum / count : Enumerable.IS_EMPTY;
}
/** @inheritdoc */
public get canReset() {
return false;
}
/** @inheritdoc */
public cast<U>(type?: string): IEnumerable<U> {
type = toStringSafe(type).trim();
return this.select((x: any) => {
if ("" !== type) {
switch (type) {
case "bool":
case "boolean":
x = !!x;
break;
case "float":
x = parseFloat(toStringSafe(x).trim());
break;
case "func":
case "function":
if ("function" !== typeof x) {
const FUNC_RESULT = x;
x = function () {
return FUNC_RESULT;
};
}
break;
case "null":
x = null;
break;
case "number":
if ("number" !== typeof x) {
x = parseFloat(toStringSafe(x).trim());
}
break;
case "object":
if (!isNullOrUndefined(x)) {
if ("object" !== typeof x) {
x = JSON.parse(toStringSafe(x));
}
}
break;
case "int":
case "integer":
x = parseInt(toStringSafe(x).trim());
break;
case "string":
x = "" + x;
break;
case "symbol":
if ("symbol" !== typeof x) {
let desc = x;
if (!isNullOrUndefined(desc)) {
if ("number" !== typeof desc) {
desc = toStringSafe(desc);
}
}
x = Symbol(desc);
}
break;
case "undefined":
x = undefined;
break;
default:
throw "Not supported type " + type;
}
}
return x;
});
}
/** @inheritdoc */
public ceil(): IEnumerable<number> {
return this.select((x) => {
return invokeForValidNumber(x, (y: number) => Math.ceil(y));
});
}
/** @inheritdoc */
public chunk(size?: number): IEnumerable<IEnumerable<T>> {
size = parseInt(toStringSafe(size).trim());
if (isNaN(size)) {
size = 1;
}
return from(this._chunkInner(size));
}
/**
* @see chunk()
*/
private *_chunkInner(size: any) {
let currentChunk;
while (true) {
const ARR = this.getNextChunkArray(size);
if (ARR.length > 0) {
yield from(ARR);
} else {
break;
}
}
}
/** @inheritdoc */
public clone<U = T>(
count?: number,
itemSelector?: Selector<T, U>,
): IEnumerable<IEnumerable<U>> {
count = parseInt(toStringSafe(count).trim());
return from(this._cloneInner(count, itemSelector));
}
/**
* @see concatArray()
*/
private *_cloneInner<U>(
count: number,
itemSelector: Selector<T, U>,
): Generator<any, void, unknown> {
const ITEMS = this.toArray();
while (true) {
if (!isNaN(count)) {
if (count-- < 1) {
break;
}
}
let seq = from(ITEMS);
if (itemSelector) {
seq = seq.select(itemSelector) as unknown as IEnumerable<T>;
}
yield seq;
}
}
/** @inheritdoc */
public concat<U = T>(...args: Sequence<U>[]): IEnumerable<T | U> {
return this.concatArray(args);
}
/** @inheritdoc */
public concatArray<U = T>(
sequences: ArrayLike<Sequence<U>>,
): IEnumerable<T | U> {
return from(this._concatArrayInner(sequences));
}
/**
* @see concatArray()
*/
private *_concatArrayInner<U>(
sequences: ArrayLike<Sequence<U>>,
): IterableIterator<T | U> {
for (let item of this) {
yield item as unknown as T;
}
if (sequences) {
for (let i = 0; i < sequences.length; i++) {
const SEQ = sequences[i];
for (let item of from(SEQ)) {
yield item;
}
}
}
}
/** @inheritdoc */
public consume() {
for (let item of this) {
}
return this;
}
/** @inheritdoc */
public contains<U>(
item: U,
comparer?: EqualityComparer<T, U> | true,
): boolean {
return this.indexOf(item, comparer) > -1;
}
/** @inheritdoc */
public cos(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.cos(y), handleAsInt),
);
}
/** @inheritdoc */
public cosH(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.cosh(y), handleAsInt),
);
}
/** @inheritdoc */
public count(predicate?: Predicate<T>): number {
predicate = toPredicateSafe(predicate);
let cnt = 0;
for (let item of this) {
if (predicate(item)) {
++cnt;
}
}
return cnt;
}
/** @inheritdoc */
public get current() {
return this._current;
}
/** @inheritdoc */
public defaultArrayIfEmpty(defaultSequence: Sequence<T>): IEnumerable<T> {
return this.defaultSequenceIfEmpty.apply(this, arguments);
}
/** @inheritdoc */
public defaultIfEmpty(...defaultItems: Array<T>): IEnumerable<T> {
return from(this._defaultIfEmptyInner(defaultItems));
}
/**
* @see defaultIfEmpty()
*/
private *_defaultIfEmptyInner(
defaultItems: Array<T>,
): Generator<T, void, unknown> {
let hasItems = false;
for (let item of this) {
hasItems = true;
yield item as unknown as T;
}
if (!hasItems && defaultItems) {
for (let item of defaultItems) {
yield item;
}
}
}
/** @inheritdoc */
public defaultSequenceIfEmpty(defaultSequence: Sequence<T>): IEnumerable<T> {
return from(this._defaultSequenceIfEmptyInner(defaultSequence));
}
/**
* @see defaultIfEmpty()
*/
private *_defaultSequenceIfEmptyInner(
defaultSequence: Sequence<T>,
): Generator<T, void, unknown> {
let hasItems = false;
for (let item of this) {
hasItems = true;
yield item as unknown as T;
}
if (!hasItems) {
for (let item of from(defaultSequence)) {
yield item;
}
}
}
/** @inheritdoc */
public distinct(comparer?: EqualityComparer<T> | true): IEnumerable<T> {
return this.distinctBy((x) => x, comparer);
}
/** @inheritdoc */
public distinctBy<U>(
selector: Selector<T, U>,
comparer?: EqualityComparer<U> | true,
): IEnumerable<T> {
if (!selector) {
selector = (i) => i as unknown as U;
}
comparer = toEqualityComparerSafe(comparer);
return from(this._distinctByInner(selector, comparer));
}
/**
* @see distinct()
*/
private *_distinctByInner<U>(
selector: Selector<T, U>,
comparer: EqualityComparer<U>,
): Generator<T, void, unknown> {
const TEMP = [];
for (let item of this) {
const KEY_ITEM = selector(item);
let found = false;
for (let t of TEMP) {
if (comparer(KEY_ITEM, t)) {
found = true;
break;
}
}
if (!found) {
TEMP.push(KEY_ITEM);
yield item;
}
}
}
/** @inheritdoc */
public each(action: EachAction<T>): this {
return this.forEach.apply(this, arguments);
}
/** @inheritdoc */
public eachAll(action: EachAction<T>): this {
return this.forAll.apply(this, arguments);
}
/** @inheritdoc */
public elementAt(index: number): T {
const ELEMENT_NOT_FOUND = Symbol("ELEMENT_NOT_FOUND");
const ITEM = this.elementAtOrDefault(index, ELEMENT_NOT_FOUND);
if (ELEMENT_NOT_FOUND === ITEM) {
throw "Element not found";
}
return ITEM;
}
/** @inheritdoc */
public elementAtOrDefault<U = Symbol>(
index: number,
defaultValue?: U,
): T | U {
index = parseInt(toStringSafe(index).trim());
if (arguments.length < 2) {
defaultValue = Enumerable.NOT_FOUND as unknown as U;
}
let i = -1;
for (let item of this) {
if (++i === index) {
return item;
}
}
return defaultValue;
}
/** @inheritdoc */
public except(
second: Sequence<T>,
comparer?: EqualityComparer<T> | true,
): IEnumerable<T> {
return from(
this._exceptInner(
from(second).distinct().toArray(),
toEqualityComparerSafe(comparer),
),
);
}
/**
* @see except()
*/
private *_exceptInner(
second: Array<T>,
comparer: EqualityComparer<T>,
): Generator<T, void, unknown> {
for (let item of this) {
let found = false;
for (let secondItem of second) {
if (comparer(item, secondItem)) {
found = true;
break;
}
}
if (!found) {
yield item;
}
}
}
/** @inheritdoc */
public exp(handleAsInt?: boolean): IEnumerable<number> {
return this.select((x) =>
invokeForValidNumber(x, (y: number) => Math.exp(y), handleAsInt),
);
}
/** @inheritdoc */
public first(predicate?: Predicate<T>): T {
predicate = toPredicateSafe(predicate);
const ELEMENT_NOT_FOUND = Symbol("ELEMENT_NOT_FOUND");
const RESULT = this.firstOrDefault(predicate, ELEMENT_NOT_FOUND);
if (ELEMENT_NOT_FOUND === RESULT) {
throw "Element not found";
}
return RESULT;
}
/** @inheritdoc */
public firstOrDefault<U = symbol>(
predicateOrDefaultValue?: Predicate<T> | T,
defaultValue?: U,
): T | U {
const ARGS = getOrDefaultArguments(
predicateOrDefaultValue,
defaultValue,
arguments.length,
);
for (let item of this) {
if (ARGS.predicate(item)) {
return item;
}
}
return ARGS.defaultValue;
}
/** @inheritdoc */
public flatten<U = T>(): IEnumerable<U> {
return this.selectMany((x) => {
return !isSequence(x) ? [x] : x;
});
}
/** @inheritdoc */
public floor(): IEnumerable<number> {
return this.select((x) => {
return invokeForValidNumber(x, (y: number) => Math.floor(y));
});
}
/** @inheritdoc */
public forAll(action: EachAction<T>): this {
const ERRORS = [];
let i = -1;
for (let item of this) {
++i;
try {
if (action) {
action(item, i);
}
} catch (e) {
ERRORS.push(new FunctionError(e, action, i));
}
}
if (ERRORS.length > 0) {
throw new AggregateError(ERRORS);
}
return this;
}
/** @inheritdoc */
public forEach(action: EachAction<T>): this {
let i = -1;
for (let item of this) {
++i;
if (action) {
action(item, i);
}
}
return this;
}
/**
* @see _chunkInner()
*/
public getNextChunkArray(size: number) {
const ARR = [];
for (let item of this) {
ARR.push(item);
if (ARR.length >= size) {
break;
}
}
return ARR;
}
/** @inheritdoc */
public groupBy<TKey>(
keySelector: Selector<T, TKey>,
keyEqualityComparer?: EqualityComparer<TKey>,
): IEnumerable<IGrouping<TKey, T>> {
if (!keySelector) {
keySelector = (i) => i as unknown as TKey;
}
keyEqualityComparer = toEqualityComparerSafe(keyEqualityComparer);
return from(this._groupByInner(keySelector, keyEqualityComparer));
}
/**
* @see groupBy()
*/
private *_groupByInner<TKey>(
keySelector: Selector<T, TKey>,
keyEqualityComparer: EqualityComparer<TKey>,
): Generator<Grouping<TKey, T>, void, unknown> {
const GROUP_LIST = [];
for (let item of this) {
const KEY = keySelector(item);
let grp;
for (let g of GROUP_LIST) {
if (keyEqualityComparer(KEY, g.key)) {
grp = g;
break;
}
}
if (!grp) {
grp = {
key: KEY,
values: <any>[],
};
GROUP_LIST.push(grp);
}
grp.values.push(item);
}
for (let grp of GROUP_LIST) {
yield new Grouping(grp.key, from(grp.values));
}
}
/** @inheritdoc */
public groupJoin<
TInner = T,
TOuterKey = any,
TInnerKey = any,
TResult = JoinedItems<T, IEnumerable<TInner>>,
>(
inner: Sequence<TInner>,
outerKeySelector?: Selector<T, TOuterKey>,
innerKeySelector?: Selector<TInner, TInnerKey>,
resultSelector?: (outer: T, inner: IEnumerable<TInner>) => TResult,
keyEqualityComparer?: EqualityComparer<TOuterKey, TInnerKey> | true,
): IEnumerable<TResult> {
if (!outerKeySelector && !innerKeySelector) {
outerKeySelector = (i) => i as unknown as TOuterKey;
innerKeySelector = outerKeySelector as unknown as Selector<
TInner,
TInnerKey
>;
} else {
if (!outerKeySelector) {
outerKeySelector = innerKeySelector as unknown as Selector<
T,
TOuterKey
>;
} else if (!innerKeySelector) {
innerKeySelector = outerKeySelector as unknown as Selector<
TInner,
TInnerKey
>;
}
}
if (!resultSelector) {
resultSelector = (_outer: any, _inner: any) => {
// JoinedItems<T, IEnumerable<TInner>>
return {
inner: _inner,
outer: _outer,
} as unknown as TResult;
};
}
keyEqualityComparer = toEqualityComparerSafe(keyEqualityComparer);
return from(
this._groupJoinInner(
from(inner),
outerKeySelector,
innerKeySelector,
resultSelector,
keyEqualityComparer,
),
);
}
/**
* @see groupJoin()
*/
private *_groupJoinInner<TInner, TOuterKey, TInnerKey, TResult>(