-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pairwise.ts
35 lines (30 loc) · 956 Bytes
/
pairwise.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
import {OperationFunction} from '../../types';
export class PairwiseIterator<T> implements IterableIterator<[T, T]> {
private prev: T | undefined;
constructor(private iterator: Iterator<T>) {}
[Symbol.iterator](): IterableIterator<[T, T]> {
return this;
}
next(): IteratorResult<[T, T]> {
for (
let item = this.iterator.next();
!item.done;
item = this.iterator.next()
) {
if (this.prev) {
const result: IteratorResult<[T, T]> = {
done: false,
value: [this.prev, item.value],
};
this.prev = item.value;
return result;
}
this.prev = item.value;
}
return {done: true, value: undefined as unknown};
}
}
/** Returns an Iterable that yields the current and the previous entry of the source Iterable. */
export function pairwise<T>(): OperationFunction<T, [T, T]> {
return entries => new PairwiseIterator(entries[Symbol.iterator]());
}