UNPKG

enum-union

Version:

TypeScript library that offers a flexible and declarative way to generate advanced enums and union types, supporting different casing styles, number-based enums, and enums from object types, enhancing type safety in TypeScript projects.

99 lines (98 loc) 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.enumKeyByVal = exports.enumKeys = exports.makeEnum = exports.Enum = void 0; function makeEnumObj(obj) { return Object.freeze(obj); } function makeEnumNumber(length, ...items) { if (items.length > length) { throw new Error(`makeEnumNumber: The number of items (${items.length}) cannot be more than the provided length (${length})`); } const obj = {}; items.forEach((key, index) => { obj[key] = index; }); obj._type = 0; return [Object.freeze(obj), Object.freeze(obj)]; } function makeEnumString(firstOrConfig, ...items) { const configOptions = [ "lowercase", "uppercase", "capitalize", "uncapitalize", ]; if (configOptions.includes(firstOrConfig)) { const enumMap = {}; items.forEach((item) => { switch (firstOrConfig) { case "lowercase": enumMap[item] = item.toLowerCase(); break; case "uppercase": enumMap[item] = item.toUpperCase(); break; case "capitalize": enumMap[item] = item.charAt(0).toUpperCase() + item.slice(1); break; case "uncapitalize": enumMap[item] = item.charAt(0).toLowerCase() + item.slice(1); break; default: enumMap[item] = item; break; } }); return [ Object.freeze(enumMap), Object.freeze(enumMap), ]; } else { const enumMap = {}; items.forEach((item) => { enumMap[item] = item; }); return [ Object.freeze(enumMap), Object.freeze(enumMap), ]; } } function Enum(firstOrConfig, ...items) { const configOptions = [ "lowercase", "uppercase", "capitalize", "uncapitalize", ]; if (typeof firstOrConfig === "object") { return makeEnumObj(firstOrConfig); } else if (typeof firstOrConfig === "number") { return makeEnumNumber(firstOrConfig, ...items); } else { const hasConfig = configOptions.includes(firstOrConfig); const configValue = hasConfig ? firstOrConfig : "enum"; const itemList = hasConfig ? items : [firstOrConfig, ...items]; return makeEnumString(configValue, ...itemList); } } exports.Enum = Enum; exports.makeEnum = Enum; function enumKeys(enumObj) { const keys = []; Object.keys(enumObj).forEach((item) => keys.push(item)); return keys; } exports.enumKeys = enumKeys; function enumKeyByVal(enumObj, val) { let key; enumKeys(enumObj).forEach(item => { if (val === enumObj[item]) key = item; }); return key; } exports.enumKeyByVal = enumKeyByVal;