-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperenum.ts
527 lines (464 loc) · 17.4 KB
/
superenum.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
Copyright ©2022-24 Ncoderz Ltd
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Enum keys
*/
export type EnumKey = string;
/**
* Enum values
*/
export type EnumValue = string | number;
/**
* Array Enum declaration
*/
export type ArrayEnum<V extends EnumValue> = V[];
/**
* Object enum declaration
*/
export type ObjectEnum<K extends EnumKey, V extends EnumValue> = { [key in K]: V };
/**
* Convert an ArrayEnum type to an ObjectEnum
*/
export type ArrayEnumToObjectEnum<T extends ReadonlyArray<EnumValue>> = {
[K in T extends ReadonlyArray<infer U> ? U : never]: T extends ReadonlyArray<infer U> ? U : never;
};
/**
* Get the type of an enum from a superenum, removing the {@link EnumExtensions} from the type
*/
export type EnumType<T> = T[keyof Omit<T, keyof EnumExtensions<EnumValue>>];
/**
* Options for the {@link Superenum} and {@link Superenum.fromArray} functions
*/
export interface EnumOptions {
iterationKeys?: ArrayEnum<EnumValue>;
noFreeze?: boolean;
}
/**
* Options for the {@link EnumExtensions.fromValue} function
*/
export interface FromValueOptions {
/**
* Ignore case when validating the enum value
*/
ignoreCase?: boolean;
}
/**
* Options for the {@link EnumExtensions.fromKey} function
*/
export interface FromKeyOptions {
/**
* Ignore case when getting the enum value from the key
*/
ignoreCase?: boolean;
}
/**
* Options for the {@link EnumExtensions.keyFromValue} function
*/
export interface KeyFromValueOptions {
/**
* Ignore case when getting the enum key from the value
*/
ignoreCase?: boolean;
}
/**
* Options for the {@link EnumExtensions.setMetadata} function
*/
export interface SetMetadataOptions {}
/**
* Options for the {@link EnumExtensions.getMetadata} function
*/
export interface GetMetadataOptions {}
export interface EnumExtensions<V extends EnumValue> {
/**
* Validate an enum value, returning the value if valid, otherwise undefined.
*
* Since a superenum is just the value, then all this function does is check to see if the value exists, and if
* so returns it, otherwise it returns undefined.
*
* Note: If the enum has duplicate values (or duplicate values when lower-cased if
* {@link FromValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate.
*
* @param value - the enum value to validate
* @param options - options for the function
* @returns the enum value, or undefined if the value cannot be matched to the enum
*/
fromValue(value: unknown | null | undefined, options?: FromValueOptions): V | undefined;
/**
* Get an enum value from its key, returning the value if key valid, otherwise undefined.
*
* Note: If the enum has duplicate keys when lower-cased if
* {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.
*
* @param key - the enum key to convert to enum value
* @param options - options for the function
* @returns the enum represented by the key, or undefined if the key cannot be matched to the enum
*/
fromKey(key: EnumKey | number | null | undefined, options?: FromKeyOptions): V | undefined;
/**
* Get an enum key from its value, returning the key if value valid, otherwise undefined.
*
* Note: If the enum has duplicate values (or duplicate values when lower-cased if
* {@link KeyFromValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate.
*
* @param value - the enum value to convert to enum key
* @param options - options for the function
* @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum
*/
keyFromValue(value: unknown | null | undefined, options?: KeyFromValueOptions): string | undefined;
/**
* Store metadata for an enum value. If value is not valid, the metadata will not be stored.
*
* @param value - the value for which to store metadata
* @param metadata - the metadata to store
* @param options - options for the function
* @returns true if the metadata was associated with the value, otherwise false
*/
setMetadata<M>(value: V | null | undefined, metadata: M, options?: SetMetadataOptions): boolean;
/**
* Retrieve metadata that was stored against an enum value.
*
* If no metadata is found, or the value is invalid, undefined will be returned.
*
* @param value - the value for which to retrieve metadata
* @param options - options for the function
* @returns the metadata associated with the enum value
*/
getMetadata<M>(value: V | null | undefined, options?: GetMetadataOptions): M | undefined;
/**
* Get an array of the enum values.
*
* Note: Item order is guaranteed unless the enum is initialised using {@link Superenum} or
* {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will
* follow the rules of the JavaScript engine which may vary. In order to guarantee the item order
* in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array
* of keys to {@link EnumOptions.iterationKeys} to represent the desired item order.
*
* https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order
*
* @returns iterator over the enum values
*/
values(): readonly V[];
/**
* Get an array of the enum keys.
*
* Note: Item order is guaranteed unless the enum is initialised using {@link Superenum} or
* {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will
* follow the rules of the JavaScript engine which may vary. In order to guarantee the item order
* in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array
* of keys to {@link EnumOptions.iterationKeys} to represent the desired item order.
*
* https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order
*
* @returns iterator over the enum values
*/
keys(): readonly EnumKey[];
/**
* Get an array of the enum entries.
*
* Note: Item order is guaranteed unless the enum is initialised using {@link Superenum} or
* {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will
* follow the rules of the JavaScript engine which may vary. In order to guarantee the item order
* in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array
* of keys to {@link EnumOptions.iterationKeys} to represent the desired item order.
*
* https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order
*
* @returns iterator over the enum values
*/
entries(): readonly [EnumKey, V][];
/**
* An iterator that iterates the enum values.
*
* Note: Iteration order is guaranteed unless the enum is initialised using {@link Superenum} or
* {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will
* follow the rules of the JavaScript engine which may vary. In order to guarantee iteration order
* in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array
* of keys to {@link EnumOptions.iterationKeys} to represent the desired iteration order.
*
* https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order
*
* @returns iterator over the enum values
*/
[Symbol.iterator](): IterableIterator<V>;
}
/**
* Interface to manage superenums
*/
export interface Superenum {
/**
* Create a superenum from a plain JavaScript object.
*
* Alias of {@link Superenum.fromObject}.
*
* @param enumeration - the plain JavaScript object enum to enhance
* @param options - options for the enum enhancement
* @returns the plain object enum converted to a superenum
*/
<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>>(
enumeration: T,
options?: EnumOptions,
): Readonly<T> & EnumExtensions<EnumType<T>>;
/**
* Create a superenum from a plain JavaScript object.
*
* The plain JavaScript object will be enhanced with {@link EnumExtensions}.
*
* Note: Item / iteration order is guaranteed unless the enum is initialised using {@link Superenum} or
* {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will
* follow the rules of the JavaScript engine which may vary. In order to guarantee the item / iteration order
* in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array
* of keys to {@link EnumOptions.iterationKeys} to represent the desired item / iteration order.
*
* Note: If the object has duplicate values, or duplicate keys or values when lower-cased, the initialisation will
* still succeed. However, the behaviour of
* {@link EnumExtensions.fromValue},
* {@link EnumExtensions.fromKey},
* {@link EnumExtensions.keyFromValue}
* will be indeterminate in cases where the keys / values clash.
*
* @param enumeration - the plain JavaScript object enum to enhance
* @param options - options for the enum enhancement
* @returns the plain object enum converted to a superenum
*/
fromObject<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>>(
enumeration: T,
options?: EnumOptions,
): Readonly<T> & EnumExtensions<EnumType<T>>;
/**
* Create a superenum from a plain JavaScript array.
*
* The array will be converted to a plain JavaScript object will be enhanced with {@link EnumExtensions}.
*
* Note: Iteration order is guaranteed to be that of the items in the array. A different iteration order can be
* specified using {@link EnumOptions.iterationKeys} to represent the desired iteration order.
*
* Note: If the array has duplicate values, the initialisation will not fail. Instead the duplicate values will
* be ignored and the resultant enum will contain just one of the values.
*
* Note: If the array has duplicate values when lower-cased, the data returned when
* calling {@link EnumExtensions.fromKey} and {@link EnumExtensions.keyFromValue} with
* *ignoreCase* set will be indeterminate for duplicate keys / values.
*
* @param enumeration - the plain JavaScript array to convert and enhance
* @param options - options for the enum enhancement
* @returns the plain array enum converted to a superenum
*/
fromArray<V extends EnumValue, T extends ArrayEnum<V>>(
enumeration: T,
options?: EnumOptions,
): Readonly<ArrayEnumToObjectEnum<T>> & EnumExtensions<EnumType<ArrayEnumToObjectEnum<T>>>;
}
function fromArray(arr: any, options?: EnumOptions) {
if (!Array.isArray(arr)) arr = [];
const enumeration = arr.reduce((acc: any, v: any) => {
acc[`${v}`] = v;
return acc;
}, {});
// Default the iteration keys to be the passed in arr if not set
if (!options || (options && !options.iterationKeys)) {
options = Object.assign({}, options);
options.iterationKeys = arr;
}
return fromObject(enumeration, options);
}
function fromObject(enumeration: any, options?: EnumOptions) {
// For reducing code size when minified
const Object_freeze = Object.freeze;
const Object_defineProperty = Object.defineProperty;
const Object_assign = Object.assign;
const definePropertyOptions = {
enumerable: false,
};
const keyValueMap = new Map<EnumKey, EnumValue>();
const valueKeyMap = new Map<EnumValue, EnumKey>();
const lcKeyValueMap = new Map<EnumKey, EnumValue>();
const lcValueKeyMap = new Map<EnumValue, EnumKey>();
const metadataMap = new Map<EnumValue, unknown>();
const iterationKeys = (options?.iterationKeys ?? Object.keys(enumeration)).map((k) => `${k}`);
// Fill keyValueMap and lcKeyValueMap
for (const [key, value] of Object.entries(enumeration)) {
// key must be a string since it's an object property
keyValueMap.set(key, value as EnumValue);
lcKeyValueMap.set(key.toLowerCase(), value as EnumValue);
}
// Fill valueKeyMap and lcValueKeyMap
for (const [key, value] of keyValueMap) {
// value might be a number, so much check
const lcValue = typeof value === 'string' ? value.toLowerCase() : value;
valueKeyMap.set(value, key);
lcValueKeyMap.set(lcValue, key);
}
const values = iterationKeys.map((k) => keyValueMap.get(k));
const entries = iterationKeys.map((k) => [k, keyValueMap.get(k)]);
const init = (options?: EnumOptions) => {
let superEn = enumeration;
// If original object is not extensible, so we have to make a copy
if (!Object.isExtensible(enumeration)) {
superEn = Object_assign({}, enumeration);
}
function fromValue(value: EnumValue, options?: FromValueOptions) {
if (options?.ignoreCase && typeof value === 'string') {
return keyValueMap.get(lcValueKeyMap.get(value.toLowerCase()) as EnumKey);
}
if (!valueKeyMap.has(value)) return undefined;
return value;
}
function fromKey(key: EnumKey | number, options?: FromKeyOptions) {
if (options?.ignoreCase && typeof key === 'string') {
return lcKeyValueMap.get(key.toLowerCase());
}
return keyValueMap.get(`${key}`);
}
function keyFromValue(value: EnumValue, options?: KeyFromValueOptions) {
if (options?.ignoreCase && typeof value === 'string') {
return lcValueKeyMap.get(value.toLowerCase());
}
return valueKeyMap.get(value);
}
function setMetadata(value: EnumValue, metadata: unknown, options?: SetMetadataOptions) {
options;
const v = fromValue(value);
if (v != null) metadataMap.set(v, metadata);
}
function getMetadata(value: EnumValue, options?: GetMetadataOptions) {
options;
return metadataMap.get(value);
}
function valueIterator() {
let i = 0;
return {
// [Symbol.iterator]() {
// return this;
// },
next: () => {
if (i < iterationKeys.length) {
return { value: keyValueMap.get(`${iterationKeys[i++]}`), done: false };
}
return {
done: true,
};
},
};
}
// Add helper functions to the enum but so they cannot be enumerated
Object_defineProperty(
superEn,
'fromKey',
Object_assign(
{
value: fromKey,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'fromValue',
Object_assign(
{
value: fromValue,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'keyFromValue',
Object_assign(
{
value: keyFromValue,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'setMetadata',
Object_assign(
{
value: setMetadata,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'getMetadata',
Object_assign(
{
value: getMetadata,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
Symbol.iterator,
Object_assign(
{
value: valueIterator,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'values',
Object_assign(
{
value: () => values,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'keys',
Object_assign(
{
value: () => iterationKeys,
},
definePropertyOptions,
),
);
Object_defineProperty(
superEn,
'entries',
Object_assign(
{
value: () => entries,
},
definePropertyOptions,
),
);
// Freeze the enum if required
let res = superEn;
if (!options?.noFreeze) {
res = Object_freeze(superEn);
Object_freeze(iterationKeys);
Object_freeze(values);
Object_freeze(entries);
}
return res;
};
return init(options);
}
const superenum: Superenum = fromObject as any;
superenum.fromObject = fromObject;
superenum.fromArray = fromArray;
export { superenum };