-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathindex.ts
More file actions
46 lines (38 loc) · 1.15 KB
/
index.ts
File metadata and controls
46 lines (38 loc) · 1.15 KB
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
import './polyfills/objectEntries';
export class Enumify {
//#################### Static
static enumKeys: Array<string>;
static enumValues: Array<Enumify>;
static closeEnum() {
const enumKeys: Array<string> = [];
const enumValues: Array<Enumify> = [];
// Traverse the enum entries
for (const [key, value] of Object.entries(this)) {
enumKeys.push(key);
value.enumKey = key;
value.enumOrdinal = enumValues.length;
enumValues.push(value);
}
// Important: only add more static properties *after* processing the enum entries
this.enumKeys = enumKeys;
this.enumValues = enumValues;
// TODO: prevent instantiation now. Freeze `this`?
}
/** Use case: parsing enum values */
static enumValueOf(str: string):undefined|Enumify {
const index = this.enumKeys.indexOf(str);
if (index >= 0) {
return this.enumValues[index];
}
return undefined;
}
static [Symbol.iterator]() {
return this.enumValues[Symbol.iterator]();
}
//#################### Instance
enumKey!: string;
enumOrdinal!: number;
toString() {
return this.constructor.name + '.' + this.enumKey;
}
}