-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
118 lines (90 loc) · 2.34 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
'use strict'
const stringify = require('safe-stable-stringify')
const isObjectLiteral = any => any?.constructor?.name === 'Object'
const kNicknameFunction = Symbol('nicknameFunction')
/**
* @class NicknameMap
*
* @extends Map
*/
class NicknameMap extends Map {
/**
* @param {Object} [options = {}]
* @param {(Boolean|Function)} [options.nicknaming]
*/
constructor (options = {}) {
if (!isObjectLiteral(options)) {
throw new Error('Expected options to be an object literal')
}
const type = typeof options.nicknaming
let nicknameFunction
switch (type) {
case 'boolean':
nicknameFunction = options.nicknaming
? NicknameMap.defaultNicknameFunction
: null
break
case 'function':
nicknameFunction = options.nicknaming
break
case 'undefined':
nicknameFunction = NicknameMap.defaultNicknameFunction
break
default:
throw new Error('Expected options.nicknaming to be a boolean or function')
}
super()
this[kNicknameFunction] = nicknameFunction
this.nicknaming = !!nicknameFunction
}
static defaultNicknameFunction (key) {
if (Array.isArray(key)) {
return '$' + key.length
}
if (isObjectLiteral(key)) {
return '%' + Object.keys(key).sort().join('%')
}
}
/**
* @param {*} key
*
* @return {Boolean}
*/
delete (key) {
const nickname = this[kNicknameFunction] && this[kNicknameFunction](key)
let count
if (nickname && !(count = super.get(nickname))) {
return false
}
const deleted = super.delete(stringify(key))
if (!deleted) return false
if (nickname) {
count === 1
? super.delete(nickname)
: super.set(nickname, count - 1)
}
return true
}
/**
* @param {*} key
*
* @return {*}
*/
get (key) {
const nickname = this[kNicknameFunction] && this[kNicknameFunction](key)
if (nickname && !super.get(nickname)) return
return super.get(stringify(key))
}
/**
* @param {*} key
*
* @param {*} value
*/
set (key, value) {
const nickname = this[kNicknameFunction] && this[kNicknameFunction](key)
super.set(stringify(key), value)
nickname && super.set(nickname, (super.get(nickname) || 0) + 1)
return this
}
}
module.exports = NicknameMap