enum-plus
Version:
A drop-in replacement for native enum. Like native enum but much better!
63 lines (60 loc) • 1.95 kB
JavaScript
import { EnumCollectionClass, EnumExtensionClass } from "./enum-collection.js";
import { localizer } from "./localize.js";
let enumExtensions;
/**
* **EN:** Enum collection interface
*
* Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you
* can only use `type`
*
* **CN:** 数组的类型声明
*
* 本来可以直接使用`EnumClass`, 但是TS不允许`class`中自定义索引访问器,只能使用`type`
*/
export const Enum = (init, options) => {
if (Array.isArray(init)) {
const initMap = getInitMapFromArray(init, options);
return new EnumCollectionClass(initMap, options);
} else {
return new EnumCollectionClass(init, options);
}
};
/*
Get or set the global localization function.
Use defineProperty here to prevent circular dependencies.
*/
Object.defineProperty(Enum, 'localize', {
get: () => localizer.localize,
set: localize => {
localizer.localize = localize;
}
});
Enum.extends = function (obj) {
if (obj !== undefined && Object.prototype.toString.call(obj) !== '[object Object]') {
throw new Error('The extension of Enum must be an object');
}
enumExtensions = obj !== undefined ? obj : {};
Object.setPrototypeOf(EnumExtensionClass.prototype, enumExtensions);
};
function getInitMapFromArray(init, options) {
const {
getValue = 'value',
getLabel = 'label',
getKey = 'key'
} = options ?? {};
return init.reduce((acc, item) => {
const value = typeof getValue === 'function' ? getValue(item) : item[getValue];
const label = typeof getLabel === 'function' ? getLabel(item) : item[getLabel];
let key = undefined;
if (getKey) {
key = typeof getKey === 'function' ? getKey(item) : item[getKey];
}
acc[key ?? value] = {
...item,
label: label || (key ?? '') || (value != null ? value.toString() : value),
value
};
return acc;
}, {});
}
//# sourceMappingURL=enum.js.map