-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path5-ready.js
More file actions
100 lines (82 loc) · 1.88 KB
/
5-ready.js
File metadata and controls
100 lines (82 loc) · 1.88 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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
// Multiple Enum implementations
class Enum {}
const enumArray = (values) => class extends Enum {
constructor(val) {
super();
this.value = this.constructor.key(val);
}
static get collection() {
return values;
}
static has(val) {
return values.includes(val);
}
static key(val) {
return values.includes(val) ? val : undefined;
}
[Symbol.toPrimitive]() {
return this.value;
}
};
const enumCollection = (values) => {
const index = {};
for (const key in values) {
const value = values[key];
index[value] = key;
}
return class extends Enum {
constructor(val) {
super();
this.value = this.constructor.key(val);
}
static get collection() {
return values;
}
static has(val) {
return !!(values[val] || index[val]);
}
static key(val) {
const value = values[val];
return value ? val : index[val];
}
[Symbol.toPrimitive](hint) {
const value = this.value;
if (hint === 'number') return parseInt(value, 10);
return values[value];
}
};
};
Enum.from = (...args) => {
const item = args[0];
const itemType = typeof item;
if (itemType === 'object') return enumCollection(item);
if (itemType !== 'string') return enumArray(args);
return enumCollection(Object.assign({}, args));
};
// Example
{
const Month = Enum.from({
Jan: 'January',
Feb: 'February',
Mar: 'March',
Apr: 'April',
May: 'May',
Jun: 'June',
Jul: 'July',
Aug: 'August',
Sep: 'September',
Oct: 'October',
Nov: 'November',
Dec: 'December'
});
console.log('Month class:');
console.log(Month);
console.log('\nMonth.collection:');
console.log(Month.collection);
if (Month.has('May')) {
const may = new Month('May');
console.log('\nMonth instance:', may);
}
console.log('\nKey for August:', Month.key('August'));
}