/
config_list.js
75 lines (59 loc) · 1.53 KB
/
config_list.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
/**
* @class
* @extends { Array }
*/
class ConfigList extends Array {
static get [Symbol.species]() { return Array }
get(key) {
const index = this.getIndex(key, true)
return this[index].value
}
append(key, value) {
return this.add({ key, value })
}
prepend(key, value) {
return this.add({ key, value }, 'prepend')
}
insert(key, value, pos = {}) {
if (!(pos.before || pos.after)) return this.append(key, value)
const currentIndex = this.getIndex(key)
if (currentIndex >= 0) this.splice(currentIndex, 1)
let newIndex = this.getIndex(pos.before || pos.after)
if (pos.after) newIndex += 1
this.splice(newIndex, 0, { key, value })
return this
}
delete(key) {
const index = this.getIndex(key, true)
this.splice(index, 1)
return this
}
getIndex(key, shouldThrow = false) {
const index = this.findIndex((entry) => (
entry === key
|| entry.key === key
|| (entry.constructor && entry.constructor.name === key)
))
if (shouldThrow && index < 0) throw new Error(`Item ${key} not found`)
return index
}
add({ key, value }, strategy = 'append') {
const index = this.getIndex(key)
if (index >= 0) this.delete(key)
switch (strategy) {
case 'prepend':
this.unshift({ key, value })
break
default:
this.push({ key, value })
}
return this
}
values() {
return this.map((item) => item.value)
}
keys() {
return this.map((item) => item.key)
}
}
module.exports = ConfigList