-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLInQer.Enumerable.ts
707 lines (666 loc) · 21.8 KB
/
LInQer.Enumerable.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
/// <reference path="./LInQer.Slim.ts" />
namespace Linqer {
export interface Enumerable extends Iterable<any> {
/**
* 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.
*
* @param {*} accumulator
* @param {(acc: any, item: any) => any} aggregator
* @returns {*}
* @memberof Enumerable
*/
aggregate(accumulator: any, aggregator: (acc: any, item: any) => any): any;
/**
* Determines whether all elements of a sequence satisfy a condition.
* @param condition
* @returns true if all
*/
all(condition: IFilter): boolean;
/**
* Determines whether any element of a sequence exists or satisfies a condition.
*
* @param {IFilter} condition
* @returns {boolean}
* @memberof Enumerable
*/
any(condition: IFilter): boolean;
/**
* Appends a value to the end of the sequence.
*
* @param {*} item
* @returns {Enumerable}
* @memberof Enumerable
*/
append(item: any): Enumerable;
/**
* Computes the average of a sequence of numeric values.
*
* @returns {(number | undefined)}
* @memberof Enumerable
*/
average(): number | undefined;
/**
* Returns itself
*
* @returns {Enumerable}
* @memberof Enumerable
*/
asEnumerable(): Enumerable;
/**
* 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.
* @param {(string | Function)} type
* @returns {Enumerable}
* @memberof Enumerable
*/
cast(type: string | Function): Enumerable;
/**
* Determines whether a sequence contains a specified element.
* A custom function can be used to determine equality between elements.
*
* @param {*} item
* @param {IEqualityComparer} equalityComparer
* @returns {boolean}
* @memberof Enumerable
*/
contains(item: any, equalityComparer: IEqualityComparer): boolean;
defaultIfEmpty(): never;
/**
* Produces the set difference of two sequences
* WARNING: using the comparer is slower
*
* @param {IterableType} iterable
* @param {IEqualityComparer} equalityComparer
* @returns {Enumerable}
* @memberof Enumerable
*/
except(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable;
/**
* Produces the set intersection of two sequences.
* WARNING: using a comparer is slower
*
* @param {IterableType} iterable
* @param {IEqualityComparer} equalityComparer
* @returns {Enumerable}
* @memberof Enumerable
*/
intersect(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable;
/**
* Same as count
*
* @returns {number}
* @memberof Enumerable
*/
longCount(): number;
/**
* 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
*
* @param {(string | Function)} type
* @returns {Enumerable}
* @memberof Enumerable
*/
ofType(type: string | Function): Enumerable;
/**
* Adds a value to the beginning of the sequence.
*
* @param {*} item
* @returns {Enumerable}
* @memberof Enumerable
*/
prepend(item: any): Enumerable;
/**
* Inverts the order of the elements in a sequence.
*
* @returns {Enumerable}
* @memberof Enumerable
*/
reverse(): Enumerable;
/**
* Projects each element of a sequence to an iterable and flattens the resulting sequences into one sequence.
*
* @param {ISelector<IterableType>} selector
* @returns {Enumerable}
* @memberof Enumerable
*/
selectMany(selector: ISelector<IterableType>): Enumerable;
/**
* Determines whether two sequences are equal and in the same order according to an optional equality comparer.
*
* @param {IterableType} iterable
* @param {IEqualityComparer} equalityComparer
* @returns {boolean}
* @memberof Enumerable
*/
sequenceEqual(iterable: IterableType, equalityComparer: IEqualityComparer): boolean;
/**
* Returns the single element of a sequence and throws if it doesn't have exactly one
*
* @returns {*}
* @memberof Enumerable
*/
single(): any;
/**
* Returns the single element of a sequence or undefined if none found. It throws if the sequence contains multiple items.
*
* @returns {(any | undefined)}
* @memberof Enumerable
*/
singleOrDefault(): any | undefined;
/**
* Returns a new enumerable collection that contains the elements from source with the last nr elements of the source collection omitted.
*
* @param {number} nr
* @returns {Enumerable}
* @memberof Enumerable
*/
skipLast(nr: number): Enumerable;
/**
* Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
*
* @param {IFilter} condition
* @returns {Enumerable}
* @memberof Enumerable
*/
skipWhile(condition: IFilter): Enumerable;
/**
* Selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
* @param start
* @param end
* @returns slice
*/
slice(start: number | undefined, end: number | undefined) : Enumerable;
/**
* Returns a new enumerable collection that contains the last nr elements from source.
*
* @param {number} nr
* @returns {Enumerable}
* @memberof Enumerable
*/
takeLast(nr: number): Enumerable;
/**
* Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.
*
* @param {IFilter} condition
* @returns {Enumerable}
* @memberof Enumerable
*/
takeWhile(condition: IFilter): Enumerable;
toDictionary(): never;
/**
* creates a Map from an Enumerable
*
* @param {ISelector} keySelector
* @param {ISelector} valueSelector
* @returns {Map<any, any>}
* @memberof Enumerable
*/
toMap(keySelector: ISelector, valueSelector: ISelector): Map<any, any>;
/**
* creates an object from an Enumerable
*
* @param {ISelector} keySelector
* @param {ISelector} valueSelector
* @returns {{ [key: string]: any }}
* @memberof Enumerable
*/
toObject(keySelector: ISelector, valueSelector: ISelector): { [key: string]: any };
toHashSet(): never;
/**
* creates a Set from an enumerable
*
* @returns {Set<any>}
* @memberof Enumerable
*/
toSet(): Set<any>;
/**
* Produces the set union of two sequences.
*
* @param {IterableType} iterable
* @param {IEqualityComparer} equalityComparer
* @returns {Enumerable}
* @memberof Enumerable
*/
union(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable;
/**
* Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
*
* @param {IterableType} iterable
* @param {(item1: any, item2: any, index: number) => any} zipper
* @returns {*}
* @memberof Enumerable
*/
zip(iterable: IterableType, zipper: (item1: any, item2: any, index: number) => any): any;
}
/// 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.
Enumerable.prototype.aggregate = function (accumulator: any, aggregator: (acc: any, item: any) => any): any {
_ensureFunction(aggregator);
for (const item of this) {
accumulator = aggregator(accumulator, item);
}
return accumulator;
}
/// Determines whether all elements of a sequence satisfy a condition.
Enumerable.prototype.all = function (condition: IFilter): boolean {
_ensureFunction(condition);
return !this.any(x => !condition(x));
}
/// Determines whether any element of a sequence exists or satisfies a condition.
Enumerable.prototype.any = function (condition: IFilter): boolean {
_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.
Enumerable.prototype.append = function (item: any): Enumerable {
return this.concat([item]);
}
/// Computes the average of a sequence of numeric values.
Enumerable.prototype.average = function (): number | undefined {
const stats = this.sumAndCount();
return stats.count === 0
? undefined
: stats.sum / stats.count;
}
/// Returns the same enumerable
Enumerable.prototype.asEnumerable = function (): Enumerable {
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.
Enumerable.prototype.cast = function (type: string | Function): Enumerable {
const f: ((x: any) => boolean) = 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.
Enumerable.prototype.contains = function (item: any, equalityComparer: IEqualityComparer = EqualityComparer.default): boolean {
_ensureFunction(equalityComparer);
return this.any(x => equalityComparer(x, item));
}
Enumerable.prototype.defaultIfEmpty = function (): never {
throw new Error('defaultIfEmpty not implemented for Javascript');
}
/// Produces the set difference of two sequences WARNING: using the comparer is slower
Enumerable.prototype.except = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable {
_ensureIterable(iterable);
const self: Enumerable = this;
// use a Set for performance if the comparer is not set
const gen = equalityComparer === EqualityComparer.default
? function* () {
const distinctValues = 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 = _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 Enumerable(gen);
}
/// Produces the set intersection of two sequences. WARNING: using a comparer is slower
Enumerable.prototype.intersect = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable {
_ensureIterable(iterable);
const self: Enumerable = this;
// use a Set for performance if the comparer is not set
const gen = equalityComparer === EqualityComparer.default
? function* () {
const distinctValues = new Set(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 = _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 Enumerable(gen);
}
/// same as count
Enumerable.prototype.longCount = function (): number {
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
Enumerable.prototype.ofType = function (type: string | Function): Enumerable {
const condition: IFilter =
typeof type === 'string'
? x => typeof x === type
: x => x instanceof type;
return this.where(condition);
}
/// Adds a value to the beginning of the sequence.
Enumerable.prototype.prepend = function (item: any): Enumerable {
return new Enumerable([item]).concat(this);
}
/// Inverts the order of the elements in a sequence.
Enumerable.prototype.reverse = function (): Enumerable {
_ensureInternalTryGetAt(this);
const self: Enumerable = 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 Enumerable(gen);
_ensureInternalCount(this);
result._count = this._count;
_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.
Enumerable.prototype.selectMany = function (selector: ISelector<IterableType>): Enumerable {
if (typeof selector !== 'undefined') {
_ensureFunction(selector);
} else {
selector = x => x;
}
const self: Enumerable = this;
const gen = function* () {
let index = 0;
for (const item of self) {
const iter = selector(item, index);
_ensureIterable(iter);
for (const child of iter) {
yield child;
}
index++;
}
};
return new Enumerable(gen);
}
/// Determines whether two sequences are equal and in the same order according to an equality comparer.
Enumerable.prototype.sequenceEqual = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): boolean {
_ensureIterable(iterable);
_ensureFunction(equalityComparer);
const iterator1 = this[Symbol.iterator]();
const iterator2 = 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
Enumerable.prototype.single = function (): any {
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.
Enumerable.prototype.singleOrDefault = function (): any | undefined {
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.
Enumerable.prototype.slice = function (start: number = 0, end: number | undefined): Enumerable {
let enumerable: 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.
Enumerable.prototype.skipLast = function (nr: number): Enumerable {
const self: Enumerable = 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++;
if (index - offset >= nrLeft) {
offset += nrLeft;
}
if (index > nrLeft) {
yield value;
}
}
buffer.length = 0;
};
const result = new Enumerable(gen);
// the count is the original count minus the skipped items and at least 0
result._count = () => Math.max(0, self.count() - nr);
_ensureInternalTryGetAt(this);
result._canSeek = this._canSeek;
// it has an indexer only if the original enumerable can seek
if (this._canSeek) {
result._tryGetAt = index => {
if (index >= result.count()) return null;
return self._tryGetAt!(index);
}
}
return result;
}
/// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
Enumerable.prototype.skipWhile = function (condition: IFilter): Enumerable {
_ensureFunction(condition);
const self: Enumerable = this;
let skip = true;
const gen = function* () {
let index = 0;
for (const item of self) {
if (skip && !condition(item, index)) {
skip = false;
}
if (!skip) {
yield item;
}
index++;
}
};
return new Enumerable(gen);
}
/// Returns a new enumerable collection that contains the last nr elements from source.
Enumerable.prototype.takeLast = function (nr: number): Enumerable {
_ensureInternalTryGetAt(this);
const self: Enumerable = this;
const gen = this._canSeek
// taking the last items is easy if the enumerable can seek
? function* () {
let nrLeft = nr;
const length = self.count();
for (let index = length - nrLeft; index < length; index++) {
yield self.elementAt(index);
}
}
// else the generator uses a buffer to fill with values
// and yields them after the entire thing has been iterated
: function* () {
let nrLeft = nr;
let index = 0;
const buffer = Array(nrLeft);
for (const item of self) {
buffer[index % nrLeft] = item;
index++;
}
for (let i = 0; i < nrLeft && i < index; i++) {
yield buffer[(index + i) % nrLeft];
}
};
const result = new Enumerable(gen);
// the count is the minimum between nr and the enumerable count
result._count = () => Math.min(nr, self.count());
result._canSeek = self._canSeek;
// this can seek only if the original enumerable could seek
if (self._canSeek) {
result._tryGetAt = index => {
if (index < 0 || index >= result.count()) return null;
return self._tryGetAt!(self.count() - nr + index);
};
}
return result;
}
/// Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.
Enumerable.prototype.takeWhile = function (condition: IFilter): Enumerable {
_ensureFunction(condition);
const self: Enumerable = this;
const gen = function* () {
let index = 0;
for (const item of self) {
if (condition(item, index)) {
yield item;
} else {
break;
}
index++;
}
};
return new Enumerable(gen);
}
Enumerable.prototype.toDictionary = function (): never {
throw new Error('use toMap or toObject instead of toDictionary');
}
/// creates a map from an Enumerable
Enumerable.prototype.toMap = function (keySelector: ISelector, valueSelector: ISelector = x => x): Map<any, any> {
_ensureFunction(keySelector);
_ensureFunction(valueSelector);
const result = new Map<any, any>();
let index = 0;
for (const item of this) {
result.set(keySelector(item, index), valueSelector(item, index));
index++;
}
return result;
}
/// creates an object from an enumerable
Enumerable.prototype.toObject = function (keySelector: ISelector, valueSelector: ISelector = x => x): { [key: string]: any } {
_ensureFunction(keySelector);
_ensureFunction(valueSelector);
const result: { [key: string]: any } = {};
let index = 0;
for (const item of this) {
result[keySelector(item, index)] = valueSelector(item);
index++;
}
return result;
}
Enumerable.prototype.toHashSet = function (): never {
throw new Error('use toSet instead of toHashSet');
}
/// creates a set from an enumerable
Enumerable.prototype.toSet = function (): Set<any> {
const result = new Set<any>();
for (const item of this) {
result.add(item);
}
return result;
}
/// Produces the set union of two sequences.
Enumerable.prototype.union = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable {
_ensureIterable(iterable);
return this.concat(iterable).distinct(equalityComparer);
}
/// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
Enumerable.prototype.zip = function (iterable: IterableType, zipper: (item1: any, item2: any, index: number) => any): any {
_ensureIterable(iterable);
if (!zipper) {
zipper = (i1,i2)=>[i1,i2];
} else {
_ensureFunction(zipper);
}
const self: Enumerable = this;
const gen = function* () {
let index = 0;
const iterator1 = self[Symbol.iterator]();
const iterator2 = Enumerable.from(iterable)[Symbol.iterator]();
let done = false;
do {
const val1 = iterator1.next();
const val2 = iterator2.next();
done = !!(val1.done || val2.done);
if (!done) {
yield zipper(val1.value, val2.value, index);
}
index++;
} while (!done);
};
return new Enumerable(gen);
}
}