1 | import { IEnumerable } from "./interface/IEnumerable";
|
2 | import IEnumerator from "./interface/IEnumerator";
|
3 |
|
4 | class CollectionEnumerator<T> implements IEnumerator<T>{
|
5 | private index = 0;
|
6 | constructor(private array: Array<T>){
|
7 | }
|
8 | next(): IEnumerator<T> {
|
9 | this.index ++;
|
10 | return this;
|
11 | }
|
12 | get Current() {
|
13 | return {
|
14 | value : this.array[this.index],
|
15 | done : this.array.length > 0 ? this.index === this.array.length - 1 : true,
|
16 | };
|
17 | }
|
18 | }
|
19 |
|
20 | export abstract class Collection<T> implements IEnumerable<T>{
|
21 | getEnumerator(): IEnumerator<T> {
|
22 | return new CollectionEnumerator(this.toArray());
|
23 | }
|
24 | public toArray(){
|
25 | const arr: Array<T> = [];
|
26 | this.__iterate((item, index) => {
|
27 | arr[index] = item;
|
28 | });
|
29 | return arr;
|
30 | }
|
31 |
|
32 | protected abstract __iterate(fn: (item: T, index: number) => void): void;
|
33 | }
|