forked from kutyel/linq.ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
750 lines (680 loc) · 20.2 KB
/
index.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
/**
* Checks if the argument passed is an object
*/
const isObj = <T>(x: T): boolean => typeof x === 'object'
/**
* Determine if two objects are equal
*/
const equal = <T, U>(a: T, b: U): boolean =>
Object.keys(a).every(
key => (isObj(a[key]) ? equal(b[key], a[key]) : b[key] === a[key])
)
/**
* Returns the index of the first item matching the predicate
*/
const findIndex = f => xs => xs.reduceRight((x, y, i) => (f(y) ? i : x))
/**
* Creates a function that negates the result of the predicate
*/
const negate = <T>(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): any => (...args) => !predicate(...args)
/**
* Comparer helpers
*/
const compare = <T>(
a: T,
b: T,
_keySelector: (key: T) => any,
descending?: boolean
): number => {
const sortKeyA = _keySelector(a)
const sortKeyB = _keySelector(b)
if (sortKeyA > sortKeyB) {
return !descending ? 1 : -1
} else if (sortKeyA < sortKeyB) {
return !descending ? -1 : 1
} else {
return 0
}
}
const composeComparers = <T>(
previousComparer: (a: T, b: T) => number,
currentComparer: (a: T, b: T) => number
): ((a: T, b: T) => number) => (a: T, b: T) =>
previousComparer(a, b) || currentComparer(a, b)
const keyComparer = <T>(
_keySelector: (key: T) => any,
descending?: boolean
): ((a: T, b: T) => number) => (a: T, b: T) =>
compare(a, b, _keySelector, descending)
/**
* LinQ to TypeScript
*
* Documentation from LinQ .NET specification (https://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx)
*
* Created by Flavio Corpa (@kutyel)
* Copyright © 2016 Flavio Corpa. All rights reserved.
*
*/
export class List<T> {
protected _elements: T[]
/**
* Defaults the elements of the list
*/
constructor(elements: T[] = []) {
this._elements = elements
}
/**
* Adds an object to the end of the List<T>.
*/
public Add(element: T): void {
this._elements.push(element)
}
/**
* Adds the elements of the specified collection to the end of the List<T>.
*/
public AddRange(elements: T[]): void {
this._elements.push(...elements)
}
/**
* Applies an accumulator function over a sequence.
*/
public Aggregate<U>(
accumulator: (accum: U, value?: T, index?: number, list?: T[]) => any,
initialValue?: U
): any {
return this._elements.reduce(accumulator, initialValue)
}
/**
* Determines whether all elements of a sequence satisfy a condition.
*/
public All(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): boolean {
return this._elements.every(predicate)
}
/**
* Determines whether a sequence contains any elements.
*/
public Any(): boolean
public Any(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): boolean
public Any(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): boolean {
return predicate
? this._elements.some(predicate)
: this._elements.length > 0
}
/**
* Computes the average of a sequence of number values that are obtained by invoking
* a transform function on each element of the input sequence.
*/
public Average(): number
public Average(
transform: (value?: T, index?: number, list?: T[]) => any
): number
public Average(
transform?: (value?: T, index?: number, list?: T[]) => any
): number {
return this.Sum(transform) / this.Count(transform)
}
/**
* Casts the elements of a sequence to the specified type.
*/
public Cast<U>(): List<U> {
return new List<U>(this._elements as any)
}
/**
* Concatenates two sequences.
*/
public Concat(list: List<T>): List<T> {
return new List<T>(this._elements.concat(list.ToArray()))
}
/**
* Determines whether an element is in the List<T>.
*/
public Contains(element: T): boolean {
return this._elements.some(x => x === element)
}
/**
* Returns the number of elements in a sequence.
*/
public Count(): number
public Count(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): number
public Count(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): number {
return predicate ? this.Where(predicate).Count() : this._elements.length
}
/**
* Returns the elements of the specified sequence or the type parameter's default value
* in a singleton collection if the sequence is empty.
*/
public DefaultIfEmpty(defaultValue?: T): List<T> {
return this.Count() ? this : new List<T>([defaultValue])
}
/**
* Returns distinct elements from a sequence by using the default equality comparer to compare values.
*/
public Distinct(): List<T> {
return this.Where(
(value, index, iter) =>
(isObj(value)
? findIndex(obj => equal(obj, value))(iter)
: iter.indexOf(value)) === index
)
}
/**
* Returns distinct elements from a sequence according to specified key selector.
*/
public DistinctBy(keySelector: (key: T) => string | number): List<T> {
const groups = this.GroupBy(keySelector)
return Object.keys(groups).reduce((res, key) => {
res.Add(groups[key][0])
return res
}, new List<T>())
}
/**
* Returns the element at a specified index in a sequence.
*/
public ElementAt(index: number): T {
if (index < this.Count()) {
return this._elements[index]
} else {
const MSG =
'ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source.'
throw new Error(MSG)
}
}
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
*/
public ElementAtOrDefault(index: number): T {
return this.ElementAt(index) || undefined
}
/**
* Produces the set difference of two sequences by using the default equality comparer to compare values.
*/
public Except(source: List<T>): List<T> {
return this.Where(x => !source.Contains(x))
}
/**
* Returns the first element of a sequence.
*/
public First(): T
public First(predicate: (value?: T, index?: number, list?: T[]) => boolean): T
public First(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): T {
if (this.Count()) {
return predicate ? this.Where(predicate).First() : this._elements[0]
} else {
throw new Error(
'InvalidOperationException: The source sequence is empty.'
)
}
}
/**
* Returns the first element of a sequence, or a default value if the sequence contains no elements.
*/
public FirstOrDefault(): T
public FirstOrDefault(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): T
public FirstOrDefault(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): T {
return this.Count(predicate) ? this.First(predicate) : undefined
}
/**
* Performs the specified action on each element of the List<T>.
*/
public ForEach(action: (value?: T, index?: number, list?: T[]) => any): void {
return this._elements.forEach(action)
}
/**
* Groups the elements of a sequence according to a specified key selector function.
*/
public GroupBy<TResult = T>(
grouper: (key: T) => string | number,
mapper?: (element: T) => TResult
): { [key: string]: TResult[] } {
const initialValue: { [key: string]: TResult[] } = {}
if (!mapper) {
mapper = val => <TResult>(<any>val)
}
return this.Aggregate((ac, v) => {
const key = grouper(v)
const existingGroup = ac[key]
const mappedValue = mapper(v)
if (existingGroup) {
existingGroup.push(mappedValue)
} else {
ac[key] = [mappedValue]
}
return ac
}, initialValue)
}
/**
* Correlates the elements of two sequences based on equality of keys and groups the results.
* The default equality comparer is used to compare keys.
*/
public GroupJoin<U>(
list: List<U>,
key1: (k: T) => any,
key2: (k: U) => any,
result: (first: T, second: List<U>) => any
): List<any> {
return this.Select((x, y) =>
result(x, list.Where(z => key1(x) === key2(z)))
)
}
/**
* Returns the index of the first occurence of an element in the List.
*/
public IndexOf(element: T): number {
return this._elements.indexOf(element)
}
/**
* Inserts an element into the List<T> at the specified index.
*/
public Insert(index: number, element: T): void | Error {
if (index < 0 || index > this._elements.length) {
throw new Error('Index is out of range.')
}
this._elements.splice(index, 0, element)
}
/**
* Produces the set intersection of two sequences by using the default equality comparer to compare values.
*/
public Intersect(source: List<T>): List<T> {
return this.Where(x => source.Contains(x))
}
/**
* Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys.
*/
public Join<U>(
list: List<U>,
key1: (key: T) => any,
key2: (key: U) => any,
result: (first: T, second: U) => any
): List<any> {
return this.SelectMany(x =>
list.Where(y => key2(y) === key1(x)).Select(z => result(x, z))
)
}
/**
* Returns the last element of a sequence.
*/
public Last(): T
public Last(predicate: (value?: T, index?: number, list?: T[]) => boolean): T
public Last(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): T {
if (this.Count()) {
return predicate
? this.Where(predicate).Last()
: this._elements[this.Count() - 1]
} else {
throw Error('InvalidOperationException: The source sequence is empty.')
}
}
/**
* Returns the last element of a sequence, or a default value if the sequence contains no elements.
*/
public LastOrDefault(): T
public LastOrDefault(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): T
public LastOrDefault(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): T {
return this.Count(predicate) ? this.Last(predicate) : undefined
}
/**
* Returns the maximum value in a generic sequence.
*/
public Max(): number
public Max(selector: (value: T, index: number, array: T[]) => number): number
public Max(
selector?: (value: T, index: number, array: T[]) => number
): number {
const id = x => x
return Math.max(...this._elements.map(selector || id))
}
/**
* Returns the minimum value in a generic sequence.
*/
public Min(): number
public Min(selector: (value: T, index: number, array: T[]) => number): number
public Min(
selector?: (value: T, index: number, array: T[]) => number
): number {
const id = x => x
return Math.min(...this._elements.map(selector || id))
}
/**
* Filters the elements of a sequence based on a specified type.
*/
public OfType<U>(type: any): List<U> {
let typeName
switch (type) {
case Number:
typeName = typeof 0
break
case String:
typeName = typeof ''
break
case Boolean:
typeName = typeof true
break
case Function:
typeName = typeof function() {} // tslint:disable-line no-empty
break
default:
typeName = null
break
}
return typeName === null
? this.Where(x => x instanceof type).Cast<U>()
: this.Where(x => typeof x === typeName).Cast<U>()
}
/**
* Sorts the elements of a sequence in ascending order according to a key.
*/
public OrderBy(
keySelector: (key: T) => any,
comparer = keyComparer(keySelector, false)
): List<T> {
return new OrderedList<T>(this._elements, comparer)
}
/**
* Sorts the elements of a sequence in descending order according to a key.
*/
public OrderByDescending(
keySelector: (key: T) => any,
comparer = keyComparer(keySelector, true)
): List<T> {
return new OrderedList<T>(this._elements, comparer)
}
/**
* Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.
*/
public ThenBy(keySelector: (key: T) => any): List<T> {
return this.OrderBy(keySelector)
}
/**
* Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.
*/
public ThenByDescending(keySelector: (key: T) => any): List<T> {
return this.OrderByDescending(keySelector)
}
/**
* Removes the first occurrence of a specific object from the List<T>.
*/
public Remove(element: T): boolean {
return this.IndexOf(element) !== -1
? (this.RemoveAt(this.IndexOf(element)), true)
: false
}
/**
* Removes all the elements that match the conditions defined by the specified predicate.
*/
public RemoveAll(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): List<T> {
return this.Where(negate(predicate))
}
/**
* Removes the element at the specified index of the List<T>.
*/
public RemoveAt(index: number): void {
this._elements.splice(index, 1)
}
/**
* Reverses the order of the elements in the entire List<T>.
*/
public Reverse(): List<T> {
return new List<T>(this._elements.reverse())
}
/**
* Projects each element of a sequence into a new form.
*/
public Select<TOut>(
selector: (element: T, index: number) => TOut
): List<TOut> {
return new List<TOut>(this._elements.map(selector))
}
/**
* Projects each element of a sequence to a List<any> and flattens the resulting sequences into one sequence.
*/
public SelectMany<TOut extends List<any>>(
selector: (element: T, index: number) => TOut
): TOut {
return this.Aggregate(
(ac, v, i) => (
ac.AddRange(
this.Select(selector)
.ElementAt(i)
.ToArray()
),
ac
),
new List<TOut>()
)
}
/**
* Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
*/
public SequenceEqual(list: List<T>): boolean {
return !!this._elements.reduce(
(x, y, z) => (list._elements[z] === y ? x : undefined)
)
}
/**
* Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
*/
public Single(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): T {
if (this.Count(predicate) !== 1) {
throw new Error('The collection does not contain exactly one element.')
} else {
return this.First(predicate)
}
}
/**
* Returns the only element of a sequence, or a default value if the sequence is empty;
* this method throws an exception if there is more than one element in the sequence.
*/
public SingleOrDefault(
predicate?: (value?: T, index?: number, list?: T[]) => boolean
): T {
return this.Count(predicate) ? this.Single(predicate) : undefined
}
/**
* Bypasses a specified number of elements in a sequence and then returns the remaining elements.
*/
public Skip(amount: number): List<T> {
return new List<T>(this._elements.slice(Math.max(0, amount)))
}
/**
* Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
*/
public SkipWhile(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): List<T> {
return this.Skip(
this.Aggregate(
(ac, val) => (predicate(this.ElementAt(ac)) ? ++ac : ac),
0
)
)
}
/**
* Computes the sum of the sequence of number values that are obtained by invoking
* a transform function on each element of the input sequence.
*/
public Sum(): number
public Sum(
transform: (value?: T, index?: number, list?: T[]) => number
): number
public Sum(
transform?: (value?: T, index?: number, list?: T[]) => number
): number {
return transform
? this.Select(transform).Sum()
: this.Aggregate((ac, v) => (ac += +v), 0)
}
/**
* Returns a specified number of contiguous elements from the start of a sequence.
*/
public Take(amount: number): List<T> {
return new List<T>(this._elements.slice(0, Math.max(0, amount)))
}
/**
* Returns elements from a sequence as long as a specified condition is true.
*/
public TakeWhile(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): List<T> {
return this.Take(
this.Aggregate(
(ac, val) => (predicate(this.ElementAt(ac)) ? ++ac : ac),
0
)
)
}
/**
* Copies the elements of the List<T> to a new array.
*/
public ToArray(): T[] {
return this._elements
}
/**
* Creates a Dictionary<TKey, TValue> from a List<T> according to a specified key selector function.
*/
public ToDictionary<TKey>(
key: (key: T) => TKey
): List<{ Key: TKey; Value: T }>
public ToDictionary<TKey, TValue>(
key: (key: T) => TKey,
value: (value: T) => TValue
): List<{ Key: TKey; Value: T | TValue }>
public ToDictionary<TKey, TValue>(
key: (key: T) => TKey,
value?: (value: T) => TValue
): List<{ Key: TKey; Value: T | TValue }> {
return this.Aggregate((dicc, v, i) => {
dicc[
this.Select(key)
.ElementAt(i)
.toString()
] = value ? this.Select(value).ElementAt(i) : v
dicc.Add({
Key: this.Select(key).ElementAt(i),
Value: value ? this.Select(value).ElementAt(i) : v
})
return dicc
}, new List<{ Key: TKey; Value: T | TValue }>())
}
/**
* Creates a List<T> from an Enumerable.List<T>.
*/
public ToList(): List<T> {
return this
}
/**
* Creates a Lookup<TKey, TElement> from an IEnumerable<T> according to specified key selector and element selector functions.
*/
public ToLookup<TResult>(
keySelector: (key: T) => string | number,
elementSelector: (element: T) => TResult
): { [key: string]: TResult[] } {
return this.GroupBy(keySelector, elementSelector)
}
/**
* Produces the set union of two sequences by using the default equality comparer.
*/
public Union(list: List<T>): List<T> {
return this.Concat(list).Distinct()
}
/**
* Filters a sequence of values based on a predicate.
*/
public Where(
predicate: (value?: T, index?: number, list?: T[]) => boolean
): List<T> {
return new List<T>(this._elements.filter(predicate))
}
/**
* Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
*/
public Zip<U, TOut>(
list: List<U>,
result: (first: T, second: U) => TOut
): List<TOut> {
return list.Count() < this.Count()
? list.Select((x, y) => result(this.ElementAt(y), x))
: this.Select((x, y) => result(x, list.ElementAt(y)))
}
}
/**
* Represents a sorted sequence. The methods of this class are implemented by using deferred execution.
* The immediate return value is an object that stores all the information that is required to perform the action.
* The query represented by this method is not executed until the object is enumerated either by
* calling its ToDictionary, ToLookup, ToList or ToArray methods
*/
class OrderedList<T> extends List<T> {
constructor(elements: T[], private _comparer: (a: T, b: T) => number) {
super(elements)
this._elements.sort(this._comparer)
}
/**
* Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.
* @override
*/
public ThenBy(keySelector: (key: T) => any): List<T> {
return new OrderedList(
this._elements,
composeComparers(this._comparer, keyComparer(keySelector, false))
)
}
/**
* Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.
* @override
*/
public ThenByDescending(keySelector: (key: T) => any): List<T> {
return new OrderedList(
this._elements,
composeComparers(this._comparer, keyComparer(keySelector, true))
)
}
}
export class Enumerable {
/**
* Generates a sequence of integral numbers within a specified range.
*/
public static Range(start: number, count: number): List<number> {
let result = new List<number>()
while (count--) {
result.Add(start++)
}
return result
}
/**
* Generates a sequence that contains one repeated value.
*/
public static Repeat<T>(element: T, count: number): List<T> {
let result = new List<T>()
while (count--) {
result.Add(element)
}
return result
}
}