-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (67 loc) · 1.84 KB
/
index.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
/**
* @typedef {Object} EnumMember
* @property {function} toJSON
* @property {function} toString
* @property {string} key
* @property {any} value
*/
module.exports = () => {
let frozen = false;
let keys = null;
/** @class */
const Mixin = class {
#enumInit(key, value) {
Object.keys(this).forEach(placeholder => {
delete this[placeholder];
});
this.key = key;
this.value = value;
}
constructor() {
if (frozen)
throw new Error("Cannot create enum value after static initialization");
}
toJSON() {
return this.value;
}
toString() {
const name = this.constructor.name;
return `[enum ${name}(${this.key})]`;
}
static byValue(value) {
return this[keys.find(key => {
return this[key] && this[key].value === value;
})];
}
static toObject() {
return keys.reduce((obj, key) => {
obj[key] = this[key].value;
return obj;
}, {});
}
static toJSON() {
return this.toObject();
}
static initialize() {
if (frozen)
return;
const base = new this();
keys = Object.keys(base);
keys.forEach(k => {
this[k] = new this();
this[k].#enumInit(k, base[k] ?? k);
Object.freeze(this[k]);
});
Object.freeze(this);
frozen = true;
}
};
return new Proxy(Mixin, {
get(target, name, cls) {
if (!frozen && name !== "prototype") {
target.initialize.call(cls);
}
return target[name];
}
});
};