-
Notifications
You must be signed in to change notification settings - Fork 72
/
slice.ts
41 lines (36 loc) · 914 Bytes
/
slice.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
import { IterableX } from './iterablex';
export class SliceIterable<TSource> extends IterableX<TSource> {
private _source: Iterable<TSource>;
private _begin: number;
private _end: number;
constructor(source: Iterable<TSource>, begin: number, end: number) {
super();
this._source = source;
this._begin = begin;
this._end = end;
}
*[Symbol.iterator]() {
let it = this._source[Symbol.iterator](),
begin = this._begin,
next;
while (begin > 0 && !(next = it.next()).done) {
begin--;
}
let end = this._end;
if (end > 0) {
while (!(next = it.next()).done) {
yield next.value;
if (--end === 0) {
break;
}
}
}
}
}
export function slice<TSource>(
source: Iterable<TSource>,
begin: number,
end: number = Infinity
): IterableX<TSource> {
return new SliceIterable<TSource>(source, begin, end);
}