-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathUtil.js
83 lines (67 loc) · 1.39 KB
/
Util.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
export const Uint32SparseSet = (length) => {
const dense = new Uint32Array(length)
const sparse = new Uint32Array(length)
let cursor = 0
dense.count = () => cursor + 1
const has = val => dense[sparse[val]] === val
const add = val => {
if (has(val)) return
sparse[val] = cursor
dense[cursor] = val
cursor++
}
const remove = val => {
if (!has(val)) return
const index = sparse[val]
const swapped = dense[cursor]
if (swapped !== val) {
dense[index] = swapped
sparse[swapped] = index
}
cursor--
}
return {
add,
remove,
has,
sparse,
dense,
}
}
export const SparseSet = () => {
const dense = []
const sparse = []
dense.sort = function (comparator) {
const result = Array.prototype.sort.call(this, comparator)
for(let i = 0; i < dense.length; i++) {
sparse[dense[i]] = i
}
return result
}
const has = val => dense[sparse[val]] === val
const add = val => {
if (has(val)) return
sparse[val] = dense.push(val) - 1
}
const remove = val => {
if (!has(val)) return
const index = sparse[val]
const swapped = dense.pop()
if (swapped !== val) {
dense[index] = swapped
sparse[swapped] = index
}
}
const reset = () => {
dense.length = 0
sparse.length = 0
}
return {
add,
remove,
has,
sparse,
dense,
reset,
}
}