-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
87 lines (85 loc) · 1.85 KB
/
index.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
84
85
86
87
export default class BidirectionalMap {
constructor(object=null) {
this._map = new Map()
this._reverse = new Map()
if (object) {
for (let attr in object) {
if ({}.hasOwnProperty.call(object, attr)) {
this.set(attr, object[attr])
}
}
}
}
get size () {
return this._map.size
}
set(key, value) {
if (this._map.has(key)) {
let _value = this._map.get(key)
this._reverse.delete(_value)
}
if (this._reverse.has(value)) {
let _key = this._reverse.get(value)
this._map.delete(_key)
}
this._map.set(key, value)
this._reverse.set(value, key)
}
get(key) {
return this._map.get(key)
}
getKey(value) {
return this._reverse.get(value)
}
clear() {
this._map.clear()
this._reverse.clear()
}
delete(key) {
let value = this._map.get(key)
this._map.delete(key)
this._reverse.delete(value)
}
deleteValue(value) {
let key = this._reverse.get(value)
this._map.delete(key)
this._reverse.delete(value)
}
entries() {
return this._map.entries()
}
has(key) {
return this._map.has(key)
}
hasValue(value) {
return this._reverse.has(value)
}
keys() {
return this._map.keys()
}
values() {
return this._map.values()
}
getObject() {
for (const key of this._map.keys()) {
if (!isPrimitive(key)) {
throw new Error('There are non-primitive keys')
}
}
return Object.fromEntries(this._map.entries())
}
getObjectReverse() {
for (const key of this._reverse.keys()) {
if (!isPrimitive(key)) {
throw new Error('There are non-primitive keys')
}
}
return Object.fromEntries(this._reverse.entries())
}
}
function isPrimitive(value) {
return (
value === null ||
!(typeof value === 'object' || typeof value === 'function')
)
}