-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path03-enum-nameof.js
83 lines (74 loc) · 2.56 KB
/
03-enum-nameof.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
80
81
82
// 03 - A better enum (with a nameOf function)
function makeEnum(name, values) {
function nameOf(value) {
let keys = Object.keys(this);
for (let index = 0; index < keys.length; index += 1) {
let key = keys[index];
if (this[key] === value) {
return `${name}.${key}`;
}
}
}
const handler = {
set (obj, prop, value) {
throw new TypeError('Enum is read only');
},
get (obj, prop) {
if (prop === 'nameOf') {
return nameOf.bind(obj);
}
if (!(prop in obj)) {
throw new ReferenceError(`Unknown enum key "${prop}"`);
}
return Reflect.get(obj, prop);
},
deleteProperty (obj, prop) {
throw new TypeError('Enum is read only');
}
};
return new Proxy(values, handler);
}
const someValue = 3;
// using a plain object as enum
console.log('Object');
const myObj = {ONE: 1, TWO: 2};
console.log(myObj.ONE); // 1 - ok
console.log(myObj.TWWO); // undefined - typos can lead to silent errors
if (myObj.ONE = someValue) { // this mistyped condition evaluates to true
console.log(myObj.ONE); // 3 - and changes our enum too
}
delete myObj.ONE; // deleted
// using a freezed object can prevent by Object.freeze)
console.log('Freezed object');
const myFrObj = Object.freeze({ONE: 1, TWO: 2});
console.log(myFrObj.ONE); // 1 - ok
console.log(myFrObj.TWWO); // undefined - typos can lead to silent errors
if (myFrObj.ONE = someValue) { // still evaluates to true
console.log(myFrObj.ONE); // 1 - but at least the modification doesn't happen
}
delete myFrObj.ONE; // no deletion, but no error either
// using a proxy as enum
console.log('Proxy');
const MyEnum = makeEnum('MyEnum', {ONE: 1, TWO: 2});
console.log(MyEnum.ONE); // 1 - ok
try {
console.log(MyEnum.TWWO); // ReferenceError - typos catched immediately
} catch(ex) {
console.error(ex);
}
try {
if (MyEnum.ONE = someValue) { // TypeError - can't be modified, doesn't evaluate, catched immediately
console.log(MyEnum.ONE); // (this line never executes)
}
} catch(ex) {
console.error(ex);
}
try {
delete MyEnum.ONE; // TypeError
} catch(ex) {
console.error(ex);
}
// trying out nameOf
console.log('nameOf' in MyEnum); // false - hidden, but accessible
console.log(MyEnum.nameOf(MyEnum.ONE)); // MyEnum.ONE
console.log(MyEnum.nameOf(1)); // MyEnum.ONE