-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
distinct.ts
31 lines (26 loc) · 855 Bytes
/
distinct.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
import {OperationFunction} from '../../types';
export class DistinctIterator<T> implements IterableIterator<T> {
private set: Set<T> = new Set<T>();
constructor(private iterator: Iterator<T>) {}
[Symbol.iterator](): IterableIterator<T> {
return this;
}
next(): IteratorResult<T> {
for (
let item = this.iterator.next();
!item.done;
item = this.iterator.next()
) {
if (!this.set.has(item.value)) {
this.set.add(item.value);
return {done: item.done, value: item.value};
}
}
this.set.clear();
return {done: true, value: undefined as unknown};
}
}
/** Returns an Iterable that yields only entries of the source Iterable without duplicates. */
export function distinct<T>(): OperationFunction<T, T> {
return entries => new DistinctIterator(entries[Symbol.iterator]());
}