enum-plus
Version:
A drop-in replacement for native enum. Like native enum but much better!
78 lines • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Enum = void 0;
const enum_collection_1 = require("./enum-collection");
const global_config_1 = require("./global-config");
const utils_1 = require("./utils");
/**
* - **EN:** Create an enum collection
* - **CN:** 创建一个枚举集合
*/
exports.Enum = ((init, options) => {
if (Array.isArray(init)) {
const initMap = getInitMapFromArray(init, options);
return new enum_collection_1.EnumCollectionClass(initMap, options);
}
else {
return new enum_collection_1.EnumCollectionClass(init, options);
}
});
/*
* Get or set the global localization function.
* Use defineProperty here to prevent circular dependencies.
*/
// Enum.config = {};
Object.defineProperty(exports.Enum, 'config', {
get: function () {
return global_config_1.internalConfig;
},
enumerable: true,
configurable: false,
});
Object.defineProperty(exports.Enum, 'localize', {
get: function () {
return global_config_1.localizer.localize;
},
set: function (localize) {
global_config_1.localizer.localize = localize;
},
enumerable: true,
configurable: false,
});
exports.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');
}
Object.defineProperties(enum_collection_1.EnumExtensionClass.prototype, Object.getOwnPropertyDescriptors(obj));
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
exports.Enum.install = (plugin, options) => {
plugin(options, exports.Enum);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
exports.Enum.isEnum = (value) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Boolean(value && typeof value === 'object' && value[utils_1.IS_ENUM] === true);
};
Object.defineProperty(exports.Enum, Symbol.hasInstance, {
value: function (instance) {
return exports.Enum.isEnum(instance);
},
writable: false,
enumerable: false,
configurable: true,
});
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