-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEnum.js
57 lines (47 loc) · 1.18 KB
/
Enum.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
/**
* Implements enums using symbols.
* Modified to use plain ES6. This code is found at
* https://gist.github.com/xmlking/e86e4f15ec32b12c4689#file-enum-es6-js-L37
* */
class EnumSymbol {
constructor(name, { value, description }) {
if (!Object.is(value, undefined)) this.value = value;
if (description) this.description = description;
this.sym = Symbol.for(name);
Object.freeze(this);
}
get display() {
return this.description || Symbol.keyFor(this.sym);
}
toString() {
return this.sym;
}
valueOf() {
return this.value;
}
}
class Enum {
constructor(enumLiterals) {
for (let key in enumLiterals) {
if (!enumLiterals[key]) throw new TypeError('each enum should have been initialized with atleast empty {} value');
this[key] = new EnumSymbol(key, enumLiterals[key]);
}
Object.freeze(this);
}
symbols() {
const result = [];
for (let key of Object.keys(this)) result.push(this[key]);
return result;
}
keys() {
return Object.keys(this);
}
contains(sym) {
if (!(sym instanceof EnumSymbol)) return false;
return this[Symbol.keyFor(sym.sym)] === sym;
}
}
module.exports = {
Enum,
EnumSymbol,
};