/
Peekable.ts
64 lines (52 loc) · 1.23 KB
/
Peekable.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
import { Option, some, none } from "../option";
import { Iter } from "./Iter";
export class Peekable<T> extends Iter<T> {
private peeked: T[] = [];
unpeekAll() {
this.peeked.length = 0;
return this;
}
unpeek(): Option<T> {
if (this.peeked.length > 0) {
return some(this.peeked.shift() as T);
} else {
return none();
}
}
peek(offset = 0): Option<T> {
if (offset < this.peeked.length) {
return some(this.peeked[offset]);
} else {
let index = this.peeked.length - offset - 1,
next = super.next();
while (!next.done) {
this.peeked.push(next.value);
if (--index <= 0) {
break;
} else {
next = super.next();
}
}
if (next.done) {
return none();
} else {
return some(next.value);
}
}
}
next(): IteratorResult<T, undefined> {
const peeked = this.unpeek();
if (peeked.isSome()) {
return { done: false, value: peeked.unwrap() };
}
const next = super.next();
if (next.done) {
return next as any;
} else {
return { done: false, value: next.value };
}
}
}
Iter.prototype.peekable = function peekable() {
return new Peekable(this);
};