-
Notifications
You must be signed in to change notification settings - Fork 4
/
SetMap.js
44 lines (40 loc) · 1.15 KB
/
SetMap.js
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
const createSetMap = () => {
const map = new Map()
const get = (mapKey, setKey) => {
const set = map.get(mapKey)
return set && set.get(setKey)
}
return {
clear: () => { map.clear() },
add: (mapKey, setKey) => {
let set = map.get(mapKey)
if (set === undefined) {
set = new Set()
map.set(mapKey, set)
}
set.add(setKey)
},
delete: (mapKey, setKey) => {
const set = map.get(mapKey)
if (!set || !set.delete(setKey)) return false
set.size === 0 && map.delete(mapKey)
return true
},
get,
has: (mapKey, setKey) => Boolean(get(mapKey, setKey)),
forEach: (callback) => { map.forEach((set, mapKey) => set.forEach((setKey) => callback(setKey, mapKey))) },
forEachSet: (callback) => { map.forEach(callback) }, // set, mapKey
forEachMap: (mapKey, callback) => {
const set = map.get(mapKey)
set && set.forEach(callback)
}
}
}
const getInvertSetMap = (sourceSetMap, targetSetMap = createSetMap()) => {
sourceSetMap.forEach((setKey, mapKey) => targetSetMap.add(setKey, mapKey))
return targetSetMap
}
export {
createSetMap,
getInvertSetMap
}