-
Notifications
You must be signed in to change notification settings - Fork 72
/
intersect.ts
50 lines (44 loc) · 1.32 KB
/
intersect.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
import { IterableX } from './iterablex';
import { arrayIndexOf } from '../internal/arrayindexof';
import { comparer as defaultComparer } from '../internal/comparer';
function arrayRemove<T>(array: T[], item: T, comparer: (x: T, y: T) => boolean): boolean {
let idx = arrayIndexOf(array, item, comparer);
if (idx === -1) {
return false;
}
array.splice(idx, 1);
return true;
}
export class IntersectIterable<TSource> extends IterableX<TSource> {
private _first: Iterable<TSource>;
private _second: Iterable<TSource>;
private _comparer: (x: TSource, y: TSource) => boolean;
constructor(
first: Iterable<TSource>,
second: Iterable<TSource>,
comparer: (x: TSource, y: TSource) => boolean
) {
super();
this._first = first;
this._second = second;
this._comparer = comparer;
}
*[Symbol.iterator]() {
let map = [] as TSource[];
for (let secondItem of this._second) {
map.push(secondItem);
}
for (let firstItem of this._first) {
if (arrayRemove(map, firstItem, this._comparer)) {
yield firstItem;
}
}
}
}
export function intersect<TSource>(
first: Iterable<TSource>,
second: Iterable<TSource>,
comparer: (x: TSource, y: TSource) => boolean = defaultComparer
): IterableX<TSource> {
return new IntersectIterable<TSource>(first, second, comparer);
}