-
Notifications
You must be signed in to change notification settings - Fork 11
/
LInQer.js
1686 lines (1686 loc) · 62.5 KB
/
LInQer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var Linqer;
(function (Linqer) {
/**
* wrapper class over iterable instances that exposes the methods usually found in .NET LINQ
*
* @export
* @class Enumerable
* @implements {Iterable<any>}
* @implements {IUsesQuickSort}
*/
class Enumerable {
/**
* You should never use this. Instead use Enumerable.from
* @param {IterableType} src
* @memberof Enumerable
*/
constructor(src) {
_ensureIterable(src);
this._src = src;
const iteratorFunction = src[Symbol.iterator];
// the generator is either the iterator of the source enumerable
// or the generator function that was provided as the source itself
if (iteratorFunction) {
this._generator = iteratorFunction.bind(src);
}
else {
this._generator = src;
}
// set sorting method on an enumerable and all the derived ones should inherit it
// TODO: a better method of doing this
this._useQuickSort = src._useQuickSort !== undefined
? src._useQuickSort
: true;
this._canSeek = false;
this._count = null;
this._tryGetAt = null;
this._wasIterated = false;
}
/**
* Wraps an iterable item into an Enumerable if it's not already one
*
* @static
* @param {IterableType} iterable
* @returns {Enumerable}
* @memberof Enumerable
*/
static from(iterable) {
if (iterable instanceof Enumerable)
return iterable;
return new Enumerable(iterable);
}
/**
* the Enumerable instance exposes the same iterator as the wrapped iterable or generator function
*
* @returns {Iterator<any>}
* @memberof Enumerable
*/
[Symbol.iterator]() {
this._wasIterated = true;
return this._generator();
}
/**
* returns an empty Enumerable
*
* @static
* @returns {Enumerable}
* @memberof Enumerable
*/
static empty() {
const result = new Enumerable([]);
result._count = () => 0;
result._tryGetAt = (index) => null;
result._canSeek = true;
return result;
}
/**
* generates a sequence of integer numbers within a specified range.
*
* @static
* @param {number} start
* @param {number} count
* @returns {Enumerable}
* @memberof Enumerable
*/
static range(start, count) {
const gen = function* () {
for (let i = 0; i < count; i++) {
yield start + i;
}
};
const result = new Enumerable(gen);
result._count = () => count;
result._tryGetAt = index => {
if (index >= 0 && index < count)
return { value: start + index };
return null;
};
result._canSeek = true;
return result;
}
/**
* Generates a sequence that contains one repeated value.
*
* @static
* @param {*} item
* @param {number} count
* @returns {Enumerable}
* @memberof Enumerable
*/
static repeat(item, count) {
const gen = function* () {
for (let i = 0; i < count; i++) {
yield item;
}
};
const result = new Enumerable(gen);
result._count = () => count;
result._tryGetAt = index => {
if (index >= 0 && index < count)
return { value: item };
return null;
};
result._canSeek = true;
return result;
}
/**
* Same value as count(), but will throw an Error if enumerable is not seekable and has to be iterated to get the length
*/
get length() {
_ensureInternalTryGetAt(this);
if (!this._canSeek)
throw new Error('Calling length on this enumerable will iterate it. Use count()');
return this.count();
}
/**
* Concatenates two sequences by appending iterable to the existing one.
*
* @param {IterableType} iterable
* @returns {Enumerable}
* @memberof Enumerable
*/
concat(iterable) {
_ensureIterable(iterable);
const self = this;
// the generator will iterate the enumerable first, then the iterable that was given as a parameter
// this will be able to seek if both the original and the iterable derived enumerable can seek
// the indexing function will get items from the first and then second enumerable without iteration
const gen = function* () {
for (const item of self) {
yield item;
}
for (const item of Enumerable.from(iterable)) {
yield item;
}
};
const result = new Enumerable(gen);
const other = Enumerable.from(iterable);
result._count = () => self.count() + other.count();
_ensureInternalTryGetAt(this);
_ensureInternalTryGetAt(other);
result._canSeek = self._canSeek && other._canSeek;
if (self._canSeek) {
result._tryGetAt = index => {
return self._tryGetAt(index) || other._tryGetAt(index - self.count());
};
}
return result;
}
/**
* Returns the number of elements in a sequence.
*
* @returns {number}
* @memberof Enumerable
*/
count() {
_ensureInternalCount(this);
return this._count();
}
/**
* Returns distinct elements from a sequence.
* WARNING: using a comparer makes this slower. Not specifying it uses a Set to determine distinctiveness.
*
* @param {IEqualityComparer} [equalityComparer=EqualityComparer.default]
* @returns {Enumerable}
* @memberof Enumerable
*/
distinct(equalityComparer = Linqer.EqualityComparer.default) {
const self = this;
// if the comparer function is not provided, a Set will be used to quickly determine distinctiveness
const gen = equalityComparer === Linqer.EqualityComparer.default
? function* () {
const distinctValues = new Set();
for (const item of self) {
const size = distinctValues.size;
distinctValues.add(item);
if (size < distinctValues.size) {
yield item;
}
}
}
// otherwise values will be compared with previous values ( O(n^2) )
// use distinctByHash in Linqer.extra to use a hashing function ( O(n log n) )
: function* () {
const values = [];
for (const item of self) {
let unique = true;
for (let i = 0; i < values.length; i++) {
if (equalityComparer(item, values[i])) {
unique = false;
break;
}
}
if (unique)
yield item;
values.push(item);
}
};
return new Enumerable(gen);
}
/**
* Returns the element at a specified index in a sequence.
*
* @param {number} index
* @returns {*}
* @memberof Enumerable
*/
elementAt(index) {
_ensureInternalTryGetAt(this);
const result = this._tryGetAt(index);
if (!result)
throw new Error('Index out of range');
return result.value;
}
/**
* Returns the element at a specified index in a sequence or undefined if the index is out of range.
*
* @param {number} index
* @returns {(any | undefined)}
* @memberof Enumerable
*/
elementAtOrDefault(index) {
_ensureInternalTryGetAt(this);
const result = this._tryGetAt(index);
if (!result)
return undefined;
return result.value;
}
/**
* Returns the first element of a sequence.
*
* @returns {*}
* @memberof Enumerable
*/
first() {
return this.elementAt(0);
}
/**
* Returns the first element of a sequence, or a default value if no element is found.
*
* @returns {(any | undefined)}
* @memberof Enumerable
*/
firstOrDefault() {
return this.elementAtOrDefault(0);
}
/**
* Returns the last element of a sequence.
*
* @returns {*}
* @memberof Enumerable
*/
last() {
_ensureInternalTryGetAt(this);
// if this cannot seek, getting the last element requires iterating the whole thing
if (!this._canSeek) {
let result = null;
let found = false;
for (const item of this) {
result = item;
found = true;
}
if (found)
return result;
throw new Error('The enumeration is empty');
}
// if this can seek, then just go directly at the last element
const count = this.count();
return this.elementAt(count - 1);
}
/**
* Returns the last element of a sequence, or undefined if no element is found.
*
* @returns {(any | undefined)}
* @memberof Enumerable
*/
lastOrDefault() {
_ensureInternalTryGetAt(this);
if (!this._canSeek) {
let result = undefined;
for (const item of this) {
result = item;
}
return result;
}
const count = this.count();
return this.elementAtOrDefault(count - 1);
}
/**
* Returns the count, minimum and maximum value in a sequence of values.
* A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller)
*
* @param {IComparer} [comparer]
* @returns {{ count: number, min: any, max: any }}
* @memberof Enumerable
*/
stats(comparer) {
if (comparer) {
_ensureFunction(comparer);
}
else {
comparer = Linqer._defaultComparer;
}
const agg = {
count: 0,
min: undefined,
max: undefined
};
for (const item of this) {
if (typeof agg.min === 'undefined' || comparer(item, agg.min) < 0)
agg.min = item;
if (typeof agg.max === 'undefined' || comparer(item, agg.max) > 0)
agg.max = item;
agg.count++;
}
return agg;
}
/**
* Returns the minimum value in a sequence of values.
* A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller)
*
* @param {IComparer} [comparer]
* @returns {*}
* @memberof Enumerable
*/
min(comparer) {
const stats = this.stats(comparer);
return stats.count === 0
? undefined
: stats.min;
}
/**
* Returns the maximum value in a sequence of values.
* A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller)
*
* @param {IComparer} [comparer]
* @returns {*}
* @memberof Enumerable
*/
max(comparer) {
const stats = this.stats(comparer);
return stats.count === 0
? undefined
: stats.max;
}
/**
* Projects each element of a sequence into a new form.
*
* @param {ISelector} selector
* @returns {Enumerable}
* @memberof Enumerable
*/
select(selector) {
_ensureFunction(selector);
const self = this;
// the generator is applying the selector on all the items of the enumerable
// the count of the resulting enumerable is the same as the original's
// the indexer is the same as that of the original, with the selector applied on the value
const gen = function* () {
let index = 0;
for (const item of self) {
yield selector(item, index);
index++;
}
};
const result = new Enumerable(gen);
_ensureInternalCount(this);
result._count = this._count;
_ensureInternalTryGetAt(self);
result._canSeek = self._canSeek;
result._tryGetAt = index => {
const res = self._tryGetAt(index);
if (!res)
return res;
return { value: selector(res.value) };
};
return result;
}
/**
* Bypasses a specified number of elements in a sequence and then returns the remaining elements.
*
* @param {number} nr
* @returns {Enumerable}
* @memberof Enumerable
*/
skip(nr) {
const self = this;
// the generator just enumerates the first nr numbers then starts yielding values
// the count is the same as the original enumerable, minus the skipped items and at least 0
// the indexer is the same as for the original, with an offset
const gen = function* () {
let nrLeft = nr;
for (const item of self) {
if (nrLeft > 0) {
nrLeft--;
}
else {
yield item;
}
}
};
const result = new Enumerable(gen);
result._count = () => Math.max(0, self.count() - nr);
_ensureInternalTryGetAt(this);
result._canSeek = this._canSeek;
result._tryGetAt = index => self._tryGetAt(index + nr);
return result;
}
/**
* Takes start elements, ignores howmany elements, continues with the new items and continues with the original enumerable
* Equivalent to the value of an array after performing splice on it with the same parameters
* @param start
* @param howmany
* @param items
* @returns splice
*/
splice(start, howmany, ...newItems) {
// tried to define length and splice so that this is seen as an Array-like object,
// but it doesn't work on properties. length needs to be a field.
return this.take(start).concat(newItems).concat(this.skip(start + howmany));
}
/**
* Computes the sum of a sequence of numeric values.
*
* @returns {(number | undefined)}
* @memberof Enumerable
*/
sum() {
const stats = this.sumAndCount();
return stats.count === 0
? undefined
: stats.sum;
}
/**
* Computes the sum and count of a sequence of numeric values.
*
* @returns {{ sum: number, count: number }}
* @memberof Enumerable
*/
sumAndCount() {
const agg = {
count: 0,
sum: 0
};
for (const item of this) {
agg.sum = agg.count === 0
? _toNumber(item)
: agg.sum + _toNumber(item);
agg.count++;
}
return agg;
}
/**
* Returns a specified number of contiguous elements from the start of a sequence.
*
* @param {number} nr
* @returns {Enumerable}
* @memberof Enumerable
*/
take(nr) {
const self = this;
// the generator will stop after nr items yielded
// the count is the maximum between the total count and nr
// the indexer is the same, as long as it's not higher than nr
const gen = function* () {
let nrLeft = nr;
for (const item of self) {
if (nrLeft > 0) {
yield item;
nrLeft--;
}
if (nrLeft <= 0) {
break;
}
}
};
const result = new Enumerable(gen);
result._count = () => Math.min(nr, self.count());
_ensureInternalTryGetAt(this);
result._canSeek = self._canSeek;
if (self._canSeek) {
result._tryGetAt = index => {
if (index >= nr)
return null;
return self._tryGetAt(index);
};
}
return result;
}
/**
* creates an array from an Enumerable
*
* @returns {any[]}
* @memberof Enumerable
*/
toArray() {
var _a;
_ensureInternalTryGetAt(this);
// this should be faster than Array.from(this)
if (this._canSeek) {
const arr = new Array(this.count());
for (let i = 0; i < arr.length; i++) {
arr[i] = (_a = this._tryGetAt(i)) === null || _a === void 0 ? void 0 : _a.value;
}
return arr;
}
// try to optimize the array growth by increasing it
// by 64 every time it is needed
const minIncrease = 64;
let size = 0;
const arr = [];
for (const item of this) {
if (size === arr.length) {
arr.length += minIncrease;
}
arr[size] = item;
size++;
}
arr.length = size;
return arr;
}
/**
* similar to toArray, but returns a seekable Enumerable (itself if already seekable) that can do count and elementAt without iterating
*
* @returns {Enumerable}
* @memberof Enumerable
*/
toList() {
_ensureInternalTryGetAt(this);
if (this._canSeek)
return this;
return Enumerable.from(this.toArray());
}
/**
* Filters a sequence of values based on a predicate.
*
* @param {IFilter} condition
* @returns {Enumerable}
* @memberof Enumerable
*/
where(condition) {
_ensureFunction(condition);
const self = this;
// cannot imply the count or indexer from the condition
// where will have to iterate through the whole thing
const gen = function* () {
let index = 0;
for (const item of self) {
if (condition(item, index)) {
yield item;
}
index++;
}
};
return new Enumerable(gen);
}
}
Linqer.Enumerable = Enumerable;
// throw if src is not a generator function or an iteratable
function _ensureIterable(src) {
if (src) {
if (src[Symbol.iterator])
return;
if (typeof src === 'function' && src.constructor.name === 'GeneratorFunction')
return;
}
throw new Error('the argument must be iterable!');
}
Linqer._ensureIterable = _ensureIterable;
// throw if f is not a function
function _ensureFunction(f) {
if (!f || typeof f !== 'function')
throw new Error('the argument needs to be a function!');
}
Linqer._ensureFunction = _ensureFunction;
// return Nan if this is not a number
// different from Number(obj), which would cast strings to numbers
function _toNumber(obj) {
return typeof obj === 'number'
? obj
: Number.NaN;
}
// return the iterable if already an array or use Array.from to create one
function _toArray(iterable) {
if (!iterable)
return [];
if (Array.isArray(iterable))
return iterable;
return Array.from(iterable);
}
Linqer._toArray = _toArray;
// if the internal count function is not defined, set it to the most appropriate one
function _ensureInternalCount(enumerable) {
if (enumerable._count)
return;
if (enumerable._src instanceof Enumerable) {
// the count is the same as the underlying enumerable
const innerEnumerable = enumerable._src;
_ensureInternalCount(innerEnumerable);
enumerable._count = () => innerEnumerable._count();
return;
}
const src = enumerable._src;
// this could cause false positives, but if it has a numeric length or size, use it
if (typeof src !== 'function' && typeof src.length === 'number') {
enumerable._count = () => src.length;
return;
}
if (typeof src.size === 'number') {
enumerable._count = () => src.size;
return;
}
// otherwise iterate the whole thing and count all items
enumerable._count = () => {
let x = 0;
for (const item of enumerable)
x++;
return x;
};
}
Linqer._ensureInternalCount = _ensureInternalCount;
// ensure there is an internal indexer function adequate for this enumerable
// this also determines if the enumerable can seek
function _ensureInternalTryGetAt(enumerable) {
if (enumerable._tryGetAt)
return;
enumerable._canSeek = true;
if (enumerable._src instanceof Enumerable) {
// indexer and seekability is the same as for the underlying enumerable
const innerEnumerable = enumerable._src;
_ensureInternalTryGetAt(innerEnumerable);
enumerable._tryGetAt = index => innerEnumerable._tryGetAt(index);
enumerable._canSeek = innerEnumerable._canSeek;
return;
}
if (typeof enumerable._src === 'string') {
// a string can be accessed by index
enumerable._tryGetAt = index => {
if (index < enumerable._src.length) {
return { value: enumerable._src.charAt(index) };
}
return null;
};
return;
}
if (Array.isArray(enumerable._src)) {
// an array can be accessed by index
enumerable._tryGetAt = index => {
if (index >= 0 && index < enumerable._src.length) {
return { value: enumerable._src[index] };
}
return null;
};
return;
}
const src = enumerable._src;
if (typeof enumerable._src !== 'function' && typeof src.length === 'number') {
// try to access an object with a defined numeric length by indexing it
// might cause false positives
enumerable._tryGetAt = index => {
if (index < src.length && typeof src[index] !== 'undefined') {
return { value: src[index] };
}
return null;
};
return;
}
enumerable._canSeek = false;
// TODO other specialized types? objects, maps, sets?
enumerable._tryGetAt = index => {
let x = 0;
for (const item of enumerable) {
if (index === x)
return { value: item };
x++;
}
return null;
};
}
Linqer._ensureInternalTryGetAt = _ensureInternalTryGetAt;
/**
* The default comparer function between two items
* @param item1
* @param item2
*/
Linqer._defaultComparer = (item1, item2) => {
if (item1 > item2)
return 1;
if (item1 < item2)
return -1;
return 0;
};
/**
* Predefined equality comparers
* default is the equivalent of ==
* exact is the equivalent of ===
*/
Linqer.EqualityComparer = {
default: (item1, item2) => item1 == item2,
exact: (item1, item2) => item1 === item2,
};
})(Linqer || (Linqer = {}));
/// <reference path="./LInQer.Slim.ts" />
var Linqer;
/// <reference path="./LInQer.Slim.ts" />
(function (Linqer) {
/// Applies an accumulator function over a sequence.
/// The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.
Linqer.Enumerable.prototype.aggregate = function (accumulator, aggregator) {
Linqer._ensureFunction(aggregator);
for (const item of this) {
accumulator = aggregator(accumulator, item);
}
return accumulator;
};
/// Determines whether all elements of a sequence satisfy a condition.
Linqer.Enumerable.prototype.all = function (condition) {
Linqer._ensureFunction(condition);
return !this.any(x => !condition(x));
};
/// Determines whether any element of a sequence exists or satisfies a condition.
Linqer.Enumerable.prototype.any = function (condition) {
Linqer._ensureFunction(condition);
let index = 0;
for (const item of this) {
if (condition(item, index))
return true;
index++;
}
return false;
};
/// Appends a value to the end of the sequence.
Linqer.Enumerable.prototype.append = function (item) {
return this.concat([item]);
};
/// Computes the average of a sequence of numeric values.
Linqer.Enumerable.prototype.average = function () {
const stats = this.sumAndCount();
return stats.count === 0
? undefined
: stats.sum / stats.count;
};
/// Returns the same enumerable
Linqer.Enumerable.prototype.asEnumerable = function () {
return this;
};
/// Checks the elements of a sequence based on their type
/// If type is a string, it will check based on typeof, else it will use instanceof.
/// Throws if types are different.
Linqer.Enumerable.prototype.cast = function (type) {
const f = typeof type === 'string'
? x => typeof x === type
: x => x instanceof type;
return this.select(item => {
if (!f(item))
throw new Error(item + ' not of type ' + type);
return item;
});
};
/// Determines whether a sequence contains a specified element.
/// A custom function can be used to determine equality between elements.
Linqer.Enumerable.prototype.contains = function (item, equalityComparer = Linqer.EqualityComparer.default) {
Linqer._ensureFunction(equalityComparer);
return this.any(x => equalityComparer(x, item));
};
Linqer.Enumerable.prototype.defaultIfEmpty = function () {
throw new Error('defaultIfEmpty not implemented for Javascript');
};
/// Produces the set difference of two sequences WARNING: using the comparer is slower
Linqer.Enumerable.prototype.except = function (iterable, equalityComparer = Linqer.EqualityComparer.default) {
Linqer._ensureIterable(iterable);
const self = this;
// use a Set for performance if the comparer is not set
const gen = equalityComparer === Linqer.EqualityComparer.default
? function* () {
const distinctValues = Linqer.Enumerable.from(iterable).toSet();
for (const item of self) {
if (!distinctValues.has(item))
yield item;
}
}
// use exceptByHash from Linqer.extra for better performance
: function* () {
const values = Linqer._toArray(iterable);
for (const item of self) {
let unique = true;
for (let i = 0; i < values.length; i++) {
if (equalityComparer(item, values[i])) {
unique = false;
break;
}
}
if (unique)
yield item;
}
};
return new Linqer.Enumerable(gen);
};
/// Produces the set intersection of two sequences. WARNING: using a comparer is slower
Linqer.Enumerable.prototype.intersect = function (iterable, equalityComparer = Linqer.EqualityComparer.default) {
Linqer._ensureIterable(iterable);
const self = this;
// use a Set for performance if the comparer is not set
const gen = equalityComparer === Linqer.EqualityComparer.default
? function* () {
const distinctValues = new Set(Linqer.Enumerable.from(iterable));
for (const item of self) {
if (distinctValues.has(item))
yield item;
}
}
// use intersectByHash from Linqer.extra for better performance
: function* () {
const values = Linqer._toArray(iterable);
for (const item of self) {
let unique = true;
for (let i = 0; i < values.length; i++) {
if (equalityComparer(item, values[i])) {
unique = false;
break;
}
}
if (!unique)
yield item;
}
};
return new Linqer.Enumerable(gen);
};
/// same as count
Linqer.Enumerable.prototype.longCount = function () {
return this.count();
};
/// Filters the elements of a sequence based on their type
/// If type is a string, it will filter based on typeof, else it will use instanceof
Linqer.Enumerable.prototype.ofType = function (type) {
const condition = typeof type === 'string'
? x => typeof x === type
: x => x instanceof type;
return this.where(condition);
};
/// Adds a value to the beginning of the sequence.
Linqer.Enumerable.prototype.prepend = function (item) {
return new Linqer.Enumerable([item]).concat(this);
};
/// Inverts the order of the elements in a sequence.
Linqer.Enumerable.prototype.reverse = function () {
Linqer._ensureInternalTryGetAt(this);
const self = this;
// if it can seek, just read the enumerable backwards
const gen = this._canSeek
? function* () {
const length = self.count();
for (let index = length - 1; index >= 0; index--) {
yield self.elementAt(index);
}
}
// else enumerate it all into an array, then read it backwards
: function* () {
const arr = self.toArray();
for (let index = arr.length - 1; index >= 0; index--) {
yield arr[index];
}
};
// the count is the same when reversed
const result = new Linqer.Enumerable(gen);
Linqer._ensureInternalCount(this);
result._count = this._count;
Linqer._ensureInternalTryGetAt(this);
// have a custom indexer only if the original enumerable could seek
if (this._canSeek) {
const self = this;
result._canSeek = true;
result._tryGetAt = index => self._tryGetAt(self.count() - index - 1);
}
return result;
};
/// Projects each element of a sequence to an iterable and flattens the resulting sequences into one sequence.
Linqer.Enumerable.prototype.selectMany = function (selector) {
if (typeof selector !== 'undefined') {
Linqer._ensureFunction(selector);
}
else {
selector = x => x;
}
const self = this;
const gen = function* () {
let index = 0;
for (const item of self) {
const iter = selector(item, index);
Linqer._ensureIterable(iter);
for (const child of iter) {
yield child;
}
index++;
}
};
return new Linqer.Enumerable(gen);
};
/// Determines whether two sequences are equal and in the same order according to an equality comparer.
Linqer.Enumerable.prototype.sequenceEqual = function (iterable, equalityComparer = Linqer.EqualityComparer.default) {
Linqer._ensureIterable(iterable);
Linqer._ensureFunction(equalityComparer);
const iterator1 = this[Symbol.iterator]();
const iterator2 = Linqer.Enumerable.from(iterable)[Symbol.iterator]();
let done = false;
do {
const val1 = iterator1.next();
const val2 = iterator2.next();
const equal = (val1.done && val2.done) || (!val1.done && !val2.done && equalityComparer(val1.value, val2.value));
if (!equal)
return false;
done = !!val1.done;
} while (!done);
return true;
};
/// Returns the single element of a sequence and throws if it doesn't have exactly one
Linqer.Enumerable.prototype.single = function () {
const iterator = this[Symbol.iterator]();
let val = iterator.next();
if (val.done)
throw new Error('Sequence contains no elements');
const result = val.value;
val = iterator.next();
if (!val.done)
throw new Error('Sequence contains more than one element');
return result;
};
/// Returns the single element of a sequence or undefined if none found. It throws if the sequence contains multiple items.
Linqer.Enumerable.prototype.singleOrDefault = function () {
const iterator = this[Symbol.iterator]();
let val = iterator.next();
if (val.done)
return undefined;
const result = val.value;
val = iterator.next();
if (!val.done)
throw new Error('Sequence contains more than one element');
return result;
};
/// Selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
Linqer.Enumerable.prototype.slice = function (start = 0, end) {
let enumerable = this;
// when the end is defined and positive and start is negative,
// the only way to compute the last index is to know the count
if (end !== undefined && end >= 0 && (start || 0) < 0) {
enumerable = enumerable.toList();
start = enumerable.count() + start;
}
if (start !== 0) {
if (start > 0) {
enumerable = enumerable.skip(start);
}
else {
enumerable = enumerable.takeLast(-start);
}
}
if (end !== undefined) {
if (end >= 0) {
enumerable = enumerable.take(end - start);
}
else {
enumerable = enumerable.skipLast(-end);
}
}
return enumerable;
};
/// Returns a new enumerable collection that contains the elements from source with the last nr elements of the source collection omitted.
Linqer.Enumerable.prototype.skipLast = function (nr) {
const self = this;
// the generator is using a buffer to cache nr values
// and only yields the values that overflow from it
const gen = function* () {
let nrLeft = nr;
const buffer = Array(nrLeft);
let index = 0;
let offset = 0;
for (const item of self) {
const value = buffer[index - offset];
buffer[index - offset] = item;
index++;