-
Notifications
You must be signed in to change notification settings - Fork 0
/
Iterable.ts
780 lines (641 loc) · 21 KB
/
Iterable.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
/// <reference path="../../../node_modules/grunt-typescript/node_modules/typescript/bin/lib.es6.d.ts"/>
/// <reference path="../../../node_modules/core-promise/core-promise.d.ts"/>
import { DefaultPromise as Promise } from "core-promise";
export interface XIterator<T> {
hasNext() : boolean;
next() : T;
}
export class XIterable<T> {
/**
* <p>Get an iterator over the iterable, that will iterate over each element.</p>
* @abstract
*/
iterator() : XIterator<T> {
throw new Error("Abstract method");
}
/**
* <p>Iterates over each element executing the given function with the element
* given as a parameter.</p>
* @param f
* @param thisParam
* @returns {Iterable}
*/
forEach( f: (it : T, index : number, iterable : XIterable<T>) => void, thisParam? : any ) : XIterable<T> {
var it = this.iterator(),
index = 0;
while (it.hasNext()) {
f.call(thisParam, it.next(), index++, this );
}
return this;
}
/**
* Promise resolves all the elements from the current collection, then invokes the
* processing callback. Afterwards resolves again all the results from the callback
* response, in order to guarantee that the result is actually just the resolved
* values of the promises.
* @param {(it: T, index: number, iterable: XIterable<T>) => void} f
* @param {any?} thisParam
* @return {Promise<XIterable<T>>}
*/
forEachPromise(f: (it: T, index: number, iterable: XIterable<T>) => void, thisParam?: any): Promise<XIterable<T>> {
return this.resolvePromises()
.then(data => data.forEach(f, thisParam))
.then(data => data.resolvePromises());
}
/**
* <p>Creates a new iterable from the giving iterable, by transforming
* each element via the function giving as argument.<p>
* @param f
* @param thisParam
* @returns {Iterable<U>}
*/
map<U>(f: (it: T, index: number, iterable: XIterable<T>) => U, thisParam?: any): XIterable<U>;
map(f: (it: T, index: number, iterable: XIterable<T>) => any, thisParam?: any): XIterable<any> {
var result = new XArrayList<any>();
this.forEach((it, index, arr) => result.add( f.call(thisParam, it, index, arr)), thisParam);
return result;
}
/**
* <p>Creates a new iterable from the giving iterable, by transforming
* each element via the function giving as argument, resolving the element with
* the Promises, and also the result.<p>
* @param f
* @param thisParam
* @returns {Iterable<U>}
*/
mapPromise<U>(f: (it: T, index: number, iterable: XIterable<T>) => U, thisParam?: any): Promise<XIterable<U>>;
mapPromise<U>(f: (it: T, index: number, iterable: XIterable<T>) => Promise<U>, thisParam?: any): Promise<XIterable<U>>;
mapPromise(f: (it: T, index: number, iterable: XIterable<T>) => any, thisParam?: any): Promise<XIterable<any>> {
return this.resolvePromises()
.then(data => data.map(f, thisParam))
.then(data => data.resolvePromises());
}
/**
* Maps the current iterable with promises.
*/
resolvePromises<T>(): Promise<XIterable<T>> {
return this.map<Promise<T>>(Promise.resolve, Promise)
.transform(c => Promise.all(c.asArray()))
.then((data) => new XArrayList<T>().addAll(data));
}
/**
* <p>Reduces the current iterable to an item that is returned by processing
* the elements in the iterable using the given function.</p>
* <p>If the initialValue is passed then reduce will iterate over each element.</p>
* <p>If the initialValue is not passed, then the first element of the iterable
* will be the initial value of the accumulator, and the callback function will be
* called for each element, starting with the second element.</p>
* @param f
* @param initialValue
* @returns {*}
*/
reduce(f: (accumulator: T, item: T, index: number, iterable: XIterable<T>) => T, initialValue?: T) : T;
reduce<TA>(f: (accumulator: TA, item: T, index: number, iterable: XIterable<T>) => T, initialValue?: TA): TA;
reduce<TU>(f: (accumulator: TU, item: T, index: number, iterable: XIterable<T>) => TU, initialValue?: TU) : TU {
var result,
firstReached = false;
if (typeof(initialValue) !== "undefined") {
result = initialValue;
firstReached = true;
}
this.forEach((it, index, iterable) => {
if (firstReached) {
result = f(result, it, index, iterable);
} else {
result = it;
firstReached = true;
}
});
return result;
}
/**
* <p>Reduces the current iterable to an item that is returned by processing
* the elements in the iterable using the given function, and resolving the promises from
* the collection if they are existing.</p>
* <p>If the initialValue is passed then reduce will iterate over each element.</p>
* <p>If the initialValue is not passed, then the first element of the iterable
* will be the initial value of the accumulator, and the callback function will be
* called for each element, starting with the second element.</p>
* @param f
* @param initialValue
* @returns {*}
*/
reducePromise(f: (accumulator: T, item: T, index: number, iterable: XIterable<T>) => T, initialValue?: T): Promise<T>;
reducePromise(f: (accumulator: T, item: T, index: number, iterable: XIterable<T>) => Promise<T>, initialValue?: T): Promise<T>;
reducePromise<TA>(f: (accumulator: TA, item: T, index: number, iterable: XIterable<T>) => T, initialValue?: TA): Promise<TA>;
reducePromise<TA>(f: (accumulator: TA, item: T, index: number, iterable: XIterable<T>) => Promise<T>, initialValue?: TA): Promise<TA>;
reducePromise<TU>(f: (accumulator: TU, item: T, index: number, iterable: XIterable<T>) => TU, initialValue?: TU): Promise<TU> {
return this.resolvePromises()
.then(data => data.reduce(f, initialValue));
}
/**
* <p>Filter all the items in the iterable, keeping only the ones where the
* condition check via the function given passes.</p>
* @param f
* @returns {XIterable<T>}
*/
filter (f : (it : T, index : number, iterable : XIterable<T>) => boolean, thisParam? : any) : XIterable<T> {
var result = new XArrayList<T>();
this.forEach((it, index, iterable) => {
if (f.call(thisParam, it, index, iterable)) {
result.add(it);
}
}, thisParam);
return result;
}
/**
* <p>Filter all the items in the iterable, keeping only the ones where the
* condition check via the function given passes.</p>
* @param f
* @returns {XIterable<T>}
*/
filterPromise(f: (it: T, index: number, iterable: XIterable<T>) => boolean, thisParam?: any): Promise<XIterable<T>>;
filterPromise(f: (it: T, index: number, iterable: XIterable<T>) => Promise < boolean>, thisParam?: any): Promise < XIterable < T >>;
filterPromise(f: (it: T, index: number, iterable: XIterable<T>) => any, thisParam?: any): Promise<XIterable<T>> {
var resolvedData;
return this.resolvePromises()
.then(data => {
resolvedData = data;
return data.mapPromise(f);
})
.then(data => {
var iterator = data.iterator();
return resolvedData.filter(() => {
return iterator.next();
});
});
}
/**
* Join multiple elements, eventually interceding the symbol.
* @param symbol
* @returns {T}
*/
join(symbol? : string) : string {
var result : string = "";
symbol = typeof symbol !== "undefined" ? symbol : ",";
this.forEach((it, index) => {
if (index == 0) {
result = "" + it;
} else {
if (symbol) {
result = result + symbol + it;
} else {
result = result + it;
}
}
});
return result;
}
/**
* <p>Finds if there is at least one element in the iterable where f(it) is true.</p>
* @param f
* @param thisParam
* @returns {boolean}
*/
some(f : (it : T, index : number, arr : XIterable<T>) => boolean, thisParam? : any) : boolean {
var iterator = this.iterator(),
index = 0;
while (iterator.hasNext()) {
if (f.call(thisParam, iterator.next(), index++, this)) {
return true;
}
}
return false;
}
/**
* Returns true if the item is in the iterable.
* @param item The items to search for in the iterable.
*/
contains(item: T): boolean {
return this.some(function (it) {
return it === item;
});
}
/**
* Returns the first element where the condition matches.
*/
findFirst(f: (it: T, index: number, arr: XIterable<T>) => boolean, thisParam?: any): T {
var iterator = this.iterator(),
index = 0,
value;
while (iterator.hasNext()) {
value = iterator.next();
if (f.call(thisParam, value, index++, this)) {
return value;
}
}
return null;
}
/**
* Returns the current iterable as a native javascript array.
* @returns {Array}
*/
asArray() : Array<T> {
var result = [];
this.forEach(it => {
result.push(it);
});
return result;
}
/**
* Returns the first element from this iterable, or null if there is no item
* in the collection..
* @returns {T}
*/
first() : T {
var it = this.iterator();
return it.hasNext() ? it.next() : null;
}
/**
* Returns an interable that has all the elements, except the first element from
* the iterable.
*/
butFirst() : XIterable<T> {
var data = this.asArray();
data.shift();
return new XArrayList<T>().addAll(data);
}
/**
* Group all the items from this iterable into a map, using the returned value from the mapping function as a key.
* @param mappingFunction
*/
groupBy<V>( mappingFunction : (it : T, index: number, arr: XIterable<T>) => V) : XMap<V, XList<T>> {
var map = new XHashMap<V, XList<T>>(),
key : V,
list : XList<T>;
this.forEach((it, index, arr) => {
key = mappingFunction(it, index, arr);
list = map.get(key);
if (!list) {
list = new XArrayList<T>();
map.put(key, list);
}
list.add(it);
});
return map;
}
/**
* Calls the given function with the iterable itself as an argument, and returns the
* result of the function.
* @param f
* @returns {V}
*/
transform<V>( f : (self : XIterable<T>) => V ) : V {
return f(this);
}
toString() : string {
return "XIterable";
}
}
/**
* A Collection of items is an Iterable object that can hold zero or more other
* objects, allowing items to be added and removed to it.
*/
export class XCollection<T> extends XIterable<T> {
/**
* Add the given element into the collection.
* @param {T} item Element to be added.
* @abstract
*/
add( item : T ) : XCollection<T> {
throw new Error("Abstract method");
}
/**
* <p>Adds all the elements from the collection given as a parameter into
* this collection.</p>
* @param {Collection<T>} items
*/
addAll( items : Array<T> ) : XCollection<T>;
addAll( items : XIterable<T> ) : XCollection<T>;
addAll( items : any ) : XCollection<T> {
if (typeof items.forEach == 'function') {
items.forEach(this.add, this);
} else {
for (var i = 0; i < items.length; i++) {
this.add( items[i] );
}
}
return this;
}
/**
* <p>Removes the element from the collection.</p>
* @param item
*/
remove(item : T) : void {
throw new Error("Abstract method");
}
/**
* <p>Returns the number of stored items in the collection.</p>
*/
size() : number {
throw new Error("Abstract method");
}
/**
* <p>Returns true if the collection has no elements.</p>
*/
isEmpty() : boolean {
throw new Error("Abstract method");
}
}
// //////////////////////////////////////////////////////////////////////////
// LIST /////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
/**
* @abstract
*/
export class XList<T> extends XCollection<T> {
get(i : number) : T {
throw new Error("Abstract method");
}
indexOf(item: T): number {
var result = -1;
this.some((it, index) => {
if (it === item) {
result = index;
return true;
}
return false;
});
return result;
}
}
/**
* An iterator specific to an array list.
*/
export class XArrayListIterator<T> implements XIterator<T> {
private list : XArrayList<T>;
private index = 0;
constructor(list : XArrayList<T>) {
this.list = list;
}
hasNext():boolean {
return this.index < this.list.storage.length;
}
next():T {
return this.list.storage[ this.index++ ];
}
}
/**
* ArrayList is a very effective implementation of a list that allows fast
* indexed access to its internal storage.
*/
export class XArrayList<T> extends XList<T> {
storage = [];
constructor(items? : XIterable<T>) {
super();
if (items) {
this.addAll( items );
}
}
iterator() : XIterator<T> {
return new XArrayListIterator(this);
}
add( o : T ) : XList<T> {
this.storage.push(o);
return this;
}
remove(o: T) {
var index = this.indexOf(o);
if (index < 0) {
throw new Error("ArrayList doesn't contain item " + o);
}
this.storage.splice(index, 1);
}
size() : number {
return this.storage.length;
}
isEmpty() : boolean {
return this.storage.length == 0;
}
get(i : number) : T {
return this.storage[i];
}
}
/**
* A list that is wrapped over an existing array, and that will
* perform all the operations on top of the initial array.
*/
export class XArrayListView<T> extends XArrayList<T> {
constructor(data) {
super(null);
this.storage = data;
}
}
// //////////////////////////////////////////////////////////////////////////
// SET //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
export class XSet<T> extends XCollection<T> {
}
export class XHashSetIterator<T> implements XIterator<T> {
private _values = [];
constructor(iteratedSet : XHashSet<T>) {
for (var key in iteratedSet._storage) {
this._values.push(key);
}
}
hasNext() : boolean {
return this._values.length > 0;
}
next() : T {
return this._values.shift();
}
}
export class XHashSet<T> extends XSet<T> {
_storage;
constructor() {
super();
this._storage = {};
}
/**
* <p>Get an iterator over the collection, that will iterate over each element.</p>
* @abstract
*/
iterator() : XIterator<T> {
return new XHashSetIterator(this);
}
/**
* Add the given element into the collection.
* @param {T} item Element to be added.
* @abstract
*/
add( item : T ) : XHashSet<T> {
this._storage[<any>item] = item;
return this;
}
/**
* <p>Removes the element from the collection.</p>
* @param item
*/
remove(item : T) : void {
delete this._storage[<any>item];
}
/**
* <p>Returns the number of stored items in the collection.</p>
*/
size() : number {
var count = 0;
for (var key in this._storage) {
count++;
}
return count;
}
/**
* <p>Returns true if the collection has no elements.</p>
*/
isEmpty() : boolean {
var key;
for (key in this._storage) {
return false;
}
return true;
}
}
// //////////////////////////////////////////////////////////////////////////
// MAP //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
export class XMapEntry<K, V> {
public constructor(public key : K,
public value: V)
{
}
}
export class XMap<K, V> extends XCollection<XMapEntry<K, V>> {
add(x : any) : XMap<K, V> {
throw new Error("Collection.add is not implemented on maps. Use map.put(key, value) instead.");
}
put(key : K, value : V) : void {
throw new Error("Abstract method");
}
get(key : K) : V {
throw new Error("Abstract method");
}
removeKey(key : K) : V {
throw new Error("Abstract method");
}
hasKey(key : K) : boolean {
throw new Error("Abstract method");
}
keys() : XIterable<K> {
throw new Error("Abstract method");
}
values() : XIterable<V> {
throw new Error("Abstract method");
}
entries() : XIterable<XMapEntry<K, V>> {
throw new Error("Abstract method");
}
iterator() : XIterator<XMapEntry<K, V>> {
return this.entries().iterator();
}
/**
* Returns the current map as an object, with its keys as properties of the object.
* @returns {Object}
*/
asObject() : Object {
var result = {};
this.forEach(function(it : XMapEntry<K, V>) {
result["" + it.key] = it.value;
});
return result;
}
}
export class XHashMap<K, V> extends XMap<K, V> {
private _storage = {};
private _elementCount = 0;
put(key : K, value : V) : void {
var k: string = "" + key;
if (!this._storage.hasOwnProperty(k)) {
this._elementCount++;
}
this._storage[k] = value;
}
get(key : K) : V {
var k : string = "" + key;
return this._storage[k];
}
removeKey(key : K) : V {
var k : string = "" + key;
var result = this._storage[k];
delete this._storage[k];
this._elementCount--;
return result;
}
hasKey(key : K) : boolean {
var k : string = "" + key;
return this._storage.hasOwnProperty(k);
}
keys() : XIterable<K> {
var k,
result : XList<K> = new XArrayList<K>();
for (k in this._storage) {
result.add(<K> k);
}
return result;
}
values() : XIterable<V> {
return this.keys().map(k => {
return this.get(k);
});
}
entries() : XIterable<XMapEntry<K, V>> {
return this.keys().map(k => {
return new XMapEntry(k, this.get(k));
});
}
size() : number {
return this._elementCount;
}
}
export class XLinkedHashMap<K, V> extends XHashMap<K, V> {
private orderedKeys: XList<K> = new XArrayList<K>();
put(key: K, value: V): void {
if (!this.orderedKeys.contains(key)) {
this.orderedKeys.add(key);
}
super.put(key, value);
}
removeKey(key: K): V {
this.orderedKeys.remove(key);
return super.removeKey(key);
}
keys(): XIterable<K> {
return this.orderedKeys;
}
}
// //////////////////////////////////////////////////////////////////////////
// UTILITY FUNCTIONS ////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
/**
* Convert the given array like items object, into a List. This
* will do a copy of the array. If you want to use the current
* items object as the actual storage of the list, use the ArrayListView
* class instead.
* @param items
*/
export function list<T>(items: Array<T>): XList<T>;
export function list<T>(items: { length: number }): XList<T>;
export function list<T>(items: any): XList<any> {
var result = new XArrayList<T>();
for (var i = 0; i < items.length; i++) {
result.add( items[i] );
}
return result;
}
/**
* Convert the given item into a XMap, using its keys as keys of the map.
* @param item
* @returns {HashMap<K, V>}
*/
export function map<K, V>(item : any) : XMap<K, V> {
var k,
result = new XHashMap<K, V>();
for (k in item) {
if (item.hasOwnProperty(k)) {
result.put(k, item[k]);
}
}
return result;
}
export function asArray<T>(item: any) : Array<T> {
return item.asArray();
}