/
Range.ts
74 lines (63 loc) · 1.46 KB
/
Range.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
import { Iter } from "../iter";
export enum RangeDirection {
Forward,
Backward,
}
export class Range implements Iterator<number>, Iterable<number> {
static from(start: number, end: number, step = 1) {
return new Range(start, end, step);
}
private start: number;
private end: number;
private step: number;
private direction: RangeDirection;
constructor(start: number, end: number, step = 1) {
this.start = start;
this.end = end;
this.step = Math.abs(step);
this.direction =
start > end ? RangeDirection.Backward : RangeDirection.Forward;
}
getStart() {
return this.start;
}
getEnd() {
return this.end;
}
getStep() {
return this.step;
}
getDirection() {
return this.direction;
}
contains(item: number) {
return this.start <= item && item <= this.end;
}
isEmpty() {
if (this.direction === RangeDirection.Forward) {
return this.start > this.end;
} else {
return this.start < this.end;
}
}
iter(): Iter<number> {
return new Iter(this);
}
[Symbol.iterator]() {
return this;
}
next(): IteratorResult<number> {
if (this.isEmpty()) {
return { done: true, value: undefined };
} else {
const value = this.start;
if (this.direction === RangeDirection.Forward) {
this.start += this.step;
} else {
this.start -= this.step;
}
return { done: false, value };
}
}
}
export const range = Range.from;