-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict.js
63 lines (57 loc) · 1.58 KB
/
dict.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
import { _ } from 'meteor/underscore';
export class Dict {
/**
* Sets up the dictionary
* @param {Object} pairs key/value pairs for the dictionary
* @parma {Object} options options for the dict
*/
constructor(pairs = {}, options) {
this.pairs = pairs;
this.throwingGet = true;
// set if it should throw an error on get if value is not found
if (options && _.has(options, 'throwingGet')) {
if (!_.isBoolean(options.throwingGet)) {
throw new Error('dict: options.throwingGet must be a Boolean.');
}
this.throwingGet = options.throwingGet;
}
this.set(this.pairs);
}
/**
* Get a value from the dictionary
* @param {String} key name of the value
* @return {<T>} found value
*/
get(key) {
let value;
if (!_.isString(key)) throw new Error('dict.get: must provide a String.');
// find value in the dict
value = this.pairs[key];
if (_.isUndefined(value) && this.throwingGet) throw Error('dict.get: value not found.');
// return the value
return value;
}
/**
* Set key/value pairs in the dictionary
* @param {Object} strings key/value pairs for the dictionary
*/
set(pairs) {
if (_.isObject(pairs)) {
// check for non strings
this._checkPairs(pairs);
_.extend(this.pairs, pairs);
} else {
throw new Error('dict.set: must provide an object.');
}
}
// check if we have only strings
_checkPairs(pairs) {
_.each(_.values(pairs), (value) => {
this._checkValue(value);
});
}
// check value
_checkValue(value) {
return true;
}
}