-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtakeWhile.ts
32 lines (27 loc) · 966 Bytes
/
takeWhile.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
import Sequence, {createSequence} from "./Sequence";
class TakeWhileIterator<T> implements Iterator<T> {
constructor(private readonly iterator: Iterator<T>,
private readonly predicate: (item: T) => boolean) {
}
next(value?: any): IteratorResult<T> {
const item = this.iterator.next();
if (!item.done) {
const result = this.predicate(item.value);
if (result) {
return {done: false, value: item.value};
}
}
return {done: true, value: undefined as any};
}
}
export class TakeWhile {
/**
* Takes all elements of the sequence as long as the given `predicate` evaluates to true.
*
* @param {(item: T) => boolean} predicate
* @returns {Sequence<T>}
*/
takeWhile<T>(this: Sequence<T>, predicate: (item: T) => boolean): Sequence<T> {
return createSequence(new TakeWhileIterator(this.iterator, predicate));
}
}