enum-plus
Version:
A drop-in replacement for native enum. Like native enum but much better!
246 lines (243 loc) • 12.6 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
import { EnumItemClass } from "./enum-item";
import { EnumItemsArray } from "./enum-values";
import { ENUM_COLLECTION, ITEMS, KEYS, VALUES } from "./utils";
/**
* **EN:** Enum collection extension base class, used to extend the Enums
*
* **CN:** 枚举集合扩展基类,用于扩展枚举
*/
// @ts-expect-error: because of typing extend in tests
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export var EnumExtensionClass = /*#__PURE__*/_createClass(function EnumExtensionClass() {
_classCallCheck(this, EnumExtensionClass);
});
/**
* **EN:** Enum collection
*
* **CN:** 枚举项集合
*/
export var EnumCollectionClass = /*#__PURE__*/function (_ref) {
_inherits(EnumCollectionClass, _ref);
var _super = _createSuper(EnumCollectionClass);
function EnumCollectionClass() {
var _this;
var init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var options = arguments.length > 1 ? arguments[1] : undefined;
_classCallCheck(this, EnumCollectionClass);
_this = _super.call(this);
// exclude number keys with a "reverse mapping" value, it means those "reverse mapping" keys of number enums
_defineProperty(_assertThisInitialized(_this), "items", void 0);
_defineProperty(_assertThisInitialized(_this), "keys", void 0);
/**
* **EN:** A boolean value indicates that this is an enum collection instance.
*
* **CN:** 布尔值,表示这是一个枚举集合实例
*/
_defineProperty(_assertThisInitialized(_this), ENUM_COLLECTION, true);
var keys = Object.keys(init).filter(function (k) {
var _init;
return !(/^-?\d+$/.test(k) && k === "".concat((_init = init[init[k]]) !== null && _init !== void 0 ? _init : ''));
});
var parsed = keys.map(function (key) {
return parseEnumItem(init[key], key);
});
keys.forEach(function (key, index) {
var value = parsed[index].value;
// @ts-expect-error: because of dynamically define property
_this[key] = value;
});
Object.freeze(keys);
// @ts-expect-error: because use KEYS to avoid naming conflicts in case of 'keys' field name is taken
_this[Object.keys(init).some(function (k) {
return k === 'keys';
}) ? KEYS : 'keys'] = keys;
// Build enum item data
var items = _construct(EnumItemsArray, [init, options].concat(_toConsumableArray(keys.map(function (key, index) {
var _parsed$index = parsed[index],
value = _parsed$index.value,
label = _parsed$index.label;
return new EnumItemClass(key, value, label, init[key], options).readonly();
}))));
// @ts-expect-error: because use ITEMS to avoid naming conflicts in case of 'items' field name is taken
_this[Object.keys(init).some(function (k) {
return k === 'items';
}) ? ITEMS : 'items'] = items;
// @ts-expect-error: because use VALUES to avoid naming conflicts in case of 'values' field name is taken
_this[Object.keys(init).some(function (k) {
return k === 'values';
}) ? VALUES : 'values'] = items;
// Override the `instanceof` operator rule
// @ts-expect-error: because override the instanceof operator
_this[Symbol.hasInstance] = function (instance) {
// intentionally use == to support both number and string format value
return _this.items.some(
// eslint-disable-next-line eqeqeq
function (i) {
return instance == i.value || instance === i.key;
});
};
Object.freeze(_assertThisInitialized(_this));
Object.freeze(_this.items);
Object.freeze(_this.keys);
return _this;
}
_createClass(EnumCollectionClass, [{
key: "key",
value: function key(value) {
return this.items.key(value);
}
}, {
key: "label",
value: function label(keyOrValue) {
return this.items.label(keyOrValue);
}
}, {
key: "has",
value: function has(keyOrValue) {
return this.items.has(keyOrValue);
}
}, {
key: "toSelect",
value: function toSelect(config) {
return this.items.toSelect(config);
}
/** @deprecated use `toSelect` instead */
}, {
key: "options",
value: function options(config) {
return this.items.options(config);
}
}, {
key: "toMenu",
value: function toMenu() {
return this.items.toMenu();
}
/** @deprecated use `toMenu` instead */
}, {
key: "menus",
value: function menus() {
return this.items.menus();
}
}, {
key: "toFilter",
value: function toFilter() {
return this.items.toFilter();
}
/** @deprecated use `toFilter` instead */
}, {
key: "filters",
value: function filters() {
return this.items.filters();
}
}, {
key: "toValueMap",
value: function toValueMap() {
return this.items.toValueMap();
}
/** @deprecated use `toValueMap` instead */
}, {
key: "valuesEnum",
value: function valuesEnum() {
return this.items.valuesEnum();
}
}, {
key: "raw",
value: function raw(value) {
if (value != null) {
return this.items.raw(value);
} else {
return this.items.raw();
}
}
}, {
key: "valueType",
get: function get() {
return this.items.valueType;
}
}, {
key: "keyType",
get: function get() {
return this.items.keyType;
}
}, {
key: "rawType",
get: function get() {
return this.items.rawType;
}
}]);
return EnumCollectionClass;
}(EnumExtensionClass);
function parseEnumItem(init, key) {
var value;
var label;
if (init != null) {
if (typeof init === 'number' || typeof init === 'string' || _typeof(init) === 'symbol') {
value = init;
label = key;
} else if (_typeof(init) === 'object') {
// Initialize using object
if (Object.prototype.toString.call(init) === '[object Object]') {
if ('value' in init && Object.keys(init).some(function (k) {
return k === 'value';
})) {
var _init$value;
// type of {value, label}
value = (_init$value = init.value) !== null && _init$value !== void 0 ? _init$value : key;
if ('label' in init && Object.keys(init).some(function (k) {
return k === 'label';
})) {
label = init.label;
} else {
label = key;
}
} else if ('label' in init && Object.keys(init).some(function (k) {
return k === 'label';
})) {
var _init$label;
// typeof {label}
value = key;
label = (_init$label = init.label) !== null && _init$label !== void 0 ? _init$label : key;
} else {
// {} empty object
value = key;
label = key;
}
} else {
// Probably Date, RegExp and other primitive types
value = init;
label = key;
}
} else {
throw new Error("Invalid enum item: ".concat(JSON.stringify(init)));
}
} else {
value = key;
label = key;
}
return {
value: value,
label: label
};
}
//# sourceMappingURL=enum-collection.js.map