-
Notifications
You must be signed in to change notification settings - Fork 2
/
enum.js
73 lines (61 loc) · 1.94 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict'
let Enum = function() {
let self = this;
let symbolToName = new Map();
let names = new Set(arguments);
if (names.size === 0) {
throw "At least one value is expected";
}
if (names.size !== arguments.length) {
let argumentsArray = Array.from(arguments);
throw "Duplicate enum value names: " +
argumentsArray.toString();
}
for(let name of names) {
if (typeof name !== 'string') throw "Name " + name.toString() +
' is of type ' + typeof name + ' but string is expected';
let sym = Symbol(name);
Object.defineProperty(this, name, {
enumerable: true,
writable:false,
configurable: false,
value: sym
});
symbolToName.set(sym, name);
}
self.size = names.size;
self.values = function() {
let values = [];
for(let value of symbolToName.keys()) {
values.push(value.toString());
}
return values
};
self.getName = function(sym) {
if (typeof sym !== 'symbol') throw "Argument " + sym.toString() +
' is of type ' + typeof sym + ' but symbol is expected';
if (!symbolToName.get(sym)) {
throw "Can't find enum value for symbol " + sym.toString();
}
return symbolToName.get(sym);
};
self.toString = function() {
let names = [];
for(let name of symbolToName.values()) {
names.push(name);
}
return names.toString();
};
self.valueOf = function(name) {
if (typeof name !== 'string') throw "Argument " + name.toString() +
' is of type ' + typeof name + ' but string is expected';
let names = [];
for(let key of symbolToName.keys()) {
if (symbolToName.get(key) == name) {
return key;
}
}
throw "Can't find symbol for name " + name;
};
Object.freeze(self);
};