enum-plus
Version:
A drop-in replacement for native enum. Like native enum but much better!
63 lines • 2.89 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.Enum = Enum;
const enum_collection_1 = require("./enum-collection");
const utils_1 = require("./utils");
let enumExtensions;
function Enum(init, options) {
if (Array.isArray(init)) {
const initMap = getInitMapFromArray(init, options);
// @ts-expect-error: because of typing extend in tests
return new enum_collection_1.EnumCollectionClass(initMap, options);
}
else {
// @ts-expect-error: because of typing extend in tests
return new enum_collection_1.EnumCollectionClass(init, options);
}
}
/**
* **EN:** Global localization function, used to convert enum item text to localized text. Only need
* to be set once, effective globally. This method need to be set at the project entry, before
* running any Enum instance
*
* If you want to provide a custom localization function, be sure to resolve and localize the
* following built-in resources:
*
* - `enum-plus.options.all` => `All`
*
* **CN:** 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效。需要在项目入口处设置,且在运行任何Enum实例之前
*
* 如果要提供自定义的本地化函数,请务必解析并本地化以下内置资源:
*
* - `enum-plus.options.all` => `All`
*/
Enum.localize = utils_1.defaultLocalize;
/**
* **EN:** Add global extension methods to the enum, and all enum instances will have these new
* extension methods
*
* **CN:** 为枚举增加全局扩展方法,所有枚举实例都会具有这些新扩展方法
*
* @param obj Extension content, must be an object | 扩展内容,必须是一个对象
*/
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(enum_collection_1.EnumExtensionClass.prototype, enumExtensions);
};
function getInitMapFromArray(init, options) {
const { getValue = 'value', getLabel = 'label', getKey = 'key' } = options !== null && options !== void 0 ? 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 !== null && key !== void 0 ? key : value)] = Object.assign(Object.assign({}, item), { label: label || (key !== null && key !== void 0 ? key : '') || (value != null ? value.toString() : value), value });
return acc;
}, {});
}
//# sourceMappingURL=enum.js.map
;