-
-
Notifications
You must be signed in to change notification settings - Fork 750
/
KeyStore.js
79 lines (62 loc) · 1.52 KB
/
KeyStore.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
import { isString, isArray } from '../helpers/types'
import * as ErrorMsg from '../core/errorMessages'
const hasOwn = Object.prototype.hasOwnProperty
export default class KeyStore {
constructor(keys) {
this._keys = []
this._keyMap = {}
let totalWeight = 0
keys.forEach((key) => {
let obj = createKey(key)
totalWeight += obj.weight
this._keys.push(obj)
this._keyMap[obj.id] = obj
totalWeight += obj.weight
})
// Normalize weights so that their sum is equal to 1
this._keys.forEach((key) => {
key.weight /= totalWeight
})
}
get(keyId) {
return this._keyMap[keyId]
}
keys() {
return this._keys
}
toJSON() {
return JSON.stringify(this._keys)
}
}
export function createKey(key) {
let path = null
let id = null
let src = null
let weight = 1
if (isString(key) || isArray(key)) {
src = key
path = createKeyPath(key)
id = createKeyId(key)
} else {
if (!hasOwn.call(key, 'name')) {
throw new Error(ErrorMsg.MISSING_KEY_PROPERTY('name'))
}
const name = key.name
src = name
if (hasOwn.call(key, 'weight')) {
weight = key.weight
if (weight <= 0) {
throw new Error(ErrorMsg.INVALID_KEY_WEIGHT_VALUE(name))
}
}
path = createKeyPath(name)
id = createKeyId(name)
}
return { path, id, weight, src }
}
export function createKeyPath(key) {
return isArray(key) ? key : key.split('.')
}
export function createKeyId(key) {
return isArray(key) ? key.join('.') : key
}