-
Notifications
You must be signed in to change notification settings - Fork 9
/
alot.ts
61 lines (52 loc) · 1.67 KB
/
alot.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
import './streams/exports'
import { AlotMeta } from './AlotMeta';
import { AlotProto } from './AlotProto';
import { IAlotStream, AlotStreamIterationResult } from './streams/IAlotStream';
export class Alot<T = any> extends AlotProto<T> {
constructor (public array: T[], public meta?: AlotMeta) {
super(new ArrayStream(array));
}
static fromObject <TValue> (obj: { [key: string]: TValue }): Alot<{ key: string, value: TValue }> {
let arr = Object.keys(obj).map(key => {
return { key, value: obj[key] };
});
return new Alot(arr);
}
static fromRange(start: number, endExcluded: number) {
let size = Math.abs(endExcluded - start);
let arr = new Array(size);
if (start <= endExcluded) {
let min = start;
let max = endExcluded;
for (let i = min; i < max; i++) {
arr[i - min] = i;
}
} else {
let min = endExcluded;
let max = start;
for (let i = max; i > min; i--) {
arr[max - i] = i;
}
}
return new Alot(arr);
}
}
export class ArrayStream<T> implements IAlotStream<T> {
isAsync = false
private index = -1;
constructor (public array: T[]) {}
next (): AlotStreamIterationResult<T> {
while (++this.index < this.array.length) {
let x = this.array[this.index];
return { value: x, done: false, index: this.index };
}
return { value: null, done: true, index: this.index };
}
async nextAsync () {
return this.next();
}
reset () {
this.index = -1;
return this;
}
}