-
Notifications
You must be signed in to change notification settings - Fork 0
/
toSet.ts
59 lines (56 loc) · 1.83 KB
/
toSet.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
51
52
53
54
55
56
57
58
59
import { IndexedSelector } from "../types/IndexedSelector";
import { SetFactory } from "../types/SetFactory";
import getIdentity from "./helpers/getIdentity";
export function _toSet<T>(src: Iterable<T>, setFactory?: SetFactory<T>): Set<T>;
export function _toSet<T, TKey>(
src: Iterable<T>,
keySelector: IndexedSelector<T, TKey>,
setFactory?: SetFactory<TKey>
): Set<TKey>;
export function _toSet<T, TKey = T>(
src: Iterable<T>,
keySelectorOrSetFactory?: IndexedSelector<T, TKey> | SetFactory<TKey>,
setFactoryMaybe?: SetFactory<TKey>
): Set<TKey> {
const ks: IndexedSelector<T, TKey> = (
typeof keySelectorOrSetFactory === "function"
? keySelectorOrSetFactory
: getIdentity()
) as IndexedSelector<T, TKey>;
const setFactory =
typeof keySelectorOrSetFactory === "object"
? keySelectorOrSetFactory
: setFactoryMaybe;
const set = setFactory?.createSet() ?? new Set();
let i = 0;
for (const x of src) {
const key = ks(x, i++);
if (set.has(key)) {
throw Error("duplicate key");
}
set.add(key);
}
return set;
}
export function toSet<T>(
setFactory?: SetFactory<T>
): (src: Iterable<T>) => Set<T>;
export function toSet<T, TKey>(
keySelector: IndexedSelector<T, TKey>,
setFactory?: SetFactory<TKey>
): (src: Iterable<T>) => Set<TKey>;
export function toSet<T, TKey = T>(
keySelectorOrSetFactory?: IndexedSelector<T, TKey> | SetFactory<TKey>,
setFactoryMaybe?: SetFactory<TKey>
): (src: Iterable<T>) => Set<TKey> {
const ks: IndexedSelector<T, TKey> = (
!(typeof keySelectorOrSetFactory === "object")
? keySelectorOrSetFactory
: getIdentity()
) as IndexedSelector<T, TKey>;
const setFactory =
typeof keySelectorOrSetFactory === "object"
? keySelectorOrSetFactory
: setFactoryMaybe;
return (src: Iterable<T>) => _toSet(src, ks, setFactory);
}