@ncoderz/superenum
Advanced tools
| "use strict";var superenum=(()=>{var e=Object.defineProperty,n=Object.getOwnPropertyDescriptor,t=Object.getOwnPropertyNames,l=Object.prototype.hasOwnProperty,r={};((n,t)=>{for(var l in t)e(n,l,{get:t[l],enumerable:!0})})(r,{Enum:()=>o});var u,f=new WeakMap;function o(e){let n=f.get(e),t=e;if(!n){let l=[];for(let n in e){let e=Number(n);!isNaN(e)&&t[t[e]]===e||l.push(n)}let r={t:l,l:new Map};for(let e of r.t){let n=t[e];r.l.set(n,e)}f.set(e,r),n=r}function l(){let e=new Map;for(let l of n.t){let n=t[l];e.set(l,n)}return n.u=e,e}function r(){let e=new Map;for(let l of n.t){let n=t[l],r="string"==typeof n?n.toLowerCase():n;e.set(r,l)}return n.o=e,e}function u(){let e=new Map;return n.i=e,e}function o(e,t){var u,f;if(null!=t&&t.ignoreCase&&"string"==typeof e){let t=null!=(u=n.u)?u:l(),o=(null!=(f=n.o)?f:r()).get(e.toLowerCase());return o?t.get(o):void 0}if(n.l.has(e))return e}function a(e,r){var u,f;let o=null!=(u=n.u)?u:l();return null!=r&&r.ignoreCase&&"string"==typeof e?(null!=(f=n.v)?f:function(){let e=new Map;for(let l of n.t){let n=t[l];e.set(l.toLowerCase(),n)}return n.v=e,e}()).get(e.toLowerCase()):o.get(`${e}`)}function i(){var e;return null!=(e=n.p)?e:function(){var e;let t=null!=(e=n.u)?e:l();return n.p=n.t.map(e=>t.get(e)),n.p}()}function c(){var e;return null!=(e=n.m)?e:function(){var e;let t=null!=(e=n.u)?e:l();return n.m=n.t.map(e=>[e,t.get(e)]),n.m}()}return{fromValue:o,fromKey:a,keyFromValue:function(e,t){var l;return null!=t&&t.ignoreCase&&"string"==typeof e?(null!=(l=n.o)?l:r()).get(e.toLowerCase()):n.l.get(e)},hasKey:function(e,n){return null!=a(e,n)},hasValue:function(e,n){return null!=o(e,n)},keys:()=>n.t,values:()=>i(),entries:()=>c(),[Symbol.iterator]:function*(){for(let e of i())yield e},setAllLabels:function(e){var t;let l=null!=(t=n.i)?t:u();for(let[n,t]of Object.entries(e)){let e=o(n);null!=e&&l.set(e,t)}},setLabels:function(e,t){var l;(null!=(l=n.i)?l:u()).set(e,t)},getLabels:function(e){var t,l;return null!=(l=(null!=(t=n.i)?t:u()).get(e))?l:{}},getLabel:function(e,t){var l,r,f;let o=null!=(r=(null!=(l=n.i)?l:u()).get(e))?r:{};if(!t)for(let n of Object.values(o))return null!=n?n:`${e}`;return null!=(f=o[t])?f:`${e}`}}}return o.fromArray=e=>{let n=e;return Array.isArray(n)||(n=[]),n.reduce((e,n)=>(e[n]=n,e),{})},u=r,((r,u,f,o)=>{if(u&&"object"==typeof u||"function"==typeof u)for(let a of t(u))!l.call(r,a)&&a!==f&&e(r,a,{get:()=>u[a],enumerable:!(o=n(u,a))||o.enumerable});return r})(e({},"__esModule",{value:!0}),u)})();//# sourceMappingURL=superenum.global.js.map |
| {"version":3,"sources":["../../src/index.ts","../../src/superenum.ts"],"sourcesContent":["export {\n Enum,\n type EnumFunc,\n type EnumType,\n type FromKeyOptions,\n type FromValueOptions,\n type HasKeyOptions,\n type HasValueOptions,\n type KeyFromValueOptions,\n type Labels,\n} from './superenum';\n","/**\n * Create an enum type from an enum like object or array.\n */\nexport type EnumType<T> = T[keyof T];\n\n/**\n * Options for the {@link Superenum.fromValue} function\n */\nexport interface FromValueOptions {\n /**\n * Ignore case when validating the enum value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.fromKey} function\n */\nexport interface FromKeyOptions {\n /**\n * Ignore case when getting the enum value from the key\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.keyFromValue} function\n */\nexport interface KeyFromValueOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.hasKey} function\n */\nexport interface HasKeyOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.hasValue} function\n */\nexport interface HasValueOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * i18n labels for enum values.\n */\nexport interface Labels {\n [key: string]: string;\n}\n\n/**\n * Array Enum declaration\n */\nexport type ArrayEnum<KV extends EnumKey> = ReadonlyArray<KV>;\n\n/**\n * Convert an ArrayEnum type to an ObjectEnum\n */\nexport type ArrayEnumToObjectEnum<T extends ReadonlyArray<string>> = {\n [K in T[number]]: K;\n};\n\nexport interface Superenum<\n K extends EnumKey = EnumKey,\n V extends EnumValue = EnumValue,\n T extends ObjectEnum<K, V> = ObjectEnum<K, V>,\n> {\n /**\n * Validate a possible enum value, returning the enum value if valid, otherwise undefined.\n *\n * Since an enum value is just the value, then all this function does is check to see if the value exists on the enum, and if\n * so returns it cast to the enum type, otherwise it returns undefined.\n *\n * Note: If the enum has duplicate values when lower-cased and\n * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to validate\n * @param options - options for the function\n * @returns the enum value, or undefined if the value cannot be matched to the enum\n */\n fromValue(value: unknown | null | undefined, options?: FromValueOptions): EnumType<T> | undefined;\n\n /**\n * Get an enum value from its key, returning the value if key valid, otherwise undefined.\n *\n * Note: If the enum has duplicate keys when lower-cased and\n * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.\n *\n * @param key - the enum key to convert to enum value\n * @param options - options for the function\n * @returns the enum represented by the key, or undefined if the key cannot be matched to the enum\n */\n fromKey(\n key: EnumKey | number | null | undefined,\n options?: FromKeyOptions,\n ): EnumType<T> | undefined;\n\n /**\n * Get an enum key from its value, returning the key if value valid, otherwise undefined.\n *\n * Note: If the enum has duplicate values when lower-cased and\n * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to convert to enum key\n * @param options - options for the function\n * @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum\n */\n keyFromValue(\n value: unknown | null | undefined,\n options?: KeyFromValueOptions,\n ): string | undefined;\n\n /**\n * Check if an enum has a value, returning true if yes, otherwise false.\n *\n * Note: If the enum has duplicate values (or duplicate values when lower-cased if\n * {@link HasValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to check\n * @param options - options for the function\n * @returns true if the enum has the value, otherwise false\n */\n hasValue(value: EnumType<T> | null | undefined, options?: HasValueOptions): boolean;\n\n /**\n * Check if an enum has a key, returning true if yes, otherwise false.\n *\n * Note: If the enum has duplicate keys when lower-cased and\n * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.\n *\n * @param key - the enum key to check\n * @param options - options for the function\n * @returns true if the enum has the key, otherwise false\n */\n hasKey(key: EnumKey | null | undefined, options?: HasKeyOptions): boolean;\n\n /**\n * Get an array of the enum values.\n *\n * @returns iterator over the enum values\n */\n values(): readonly EnumType<T>[];\n\n /**\n * Get an array of the enum keys.\n *\n * @returns iterator over the enum values\n */\n keys(): readonly ExtractEnumKey<K, V, T>[];\n\n /**\n * Get an array of the enum entries.\n *\n * @returns iterator over the enum values\n */\n entries(): readonly [ExtractEnumKey<K, V, T>, EnumType<T>][];\n\n /**\n * An iterator that iterates the enum values.\n *\n * @returns iterator over the enum values\n */\n [Symbol.iterator](): IterableIterator<EnumType<T>>;\n\n /**\n * Set i18n labels for all enum values.\n *\n * @param allLabels - an object containing i18n labels for each enum value\n */\n setAllLabels(allLabels: { [key: EnumValue]: Labels }): void;\n\n /**\n * Set i18n labels for a specific enum value.\n *\n * @param value - the enum value to set i18n labels for\n * @param labels - an object containing i18n labels for the enum value\n */\n setLabels(value: EnumType<T>, labels: Labels): void;\n\n /**\n * Get i18n labels for a specific enum value.\n *\n * @param value - the enum value to get i18n labels for\n * @returns an object containing i18n labels for the enum value\n */\n getLabels(value: EnumType<T>): Labels;\n\n /**\n * Get a label for a specific enum value in a specific locale.\n *\n * If no locale is provided, it will return the first label that was set.\n * If no label is found for the value, it will return the value as a string.\n *\n * @param value - the enum value to get the label for\n * @param locale - the locale to get the label for\n * @returns the label for the enum value in the specified locale\n */\n getLabel(value: EnumType<T>, locale?: string): string;\n}\n\ntype EnumKey = string;\ntype EnumValue = string | number;\ntype ExtractEnumKey<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>> = keyof T;\n\ntype GenericEnum = Readonly<Record<EnumKey, EnumValue>>;\n\ntype ObjectEnum<K extends EnumKey, V extends EnumValue> = { [key in K]: V };\n\ninterface Cache {\n _keys: EnumKey[];\n _valueKeyMap: Map<EnumValue, EnumKey>;\n _keyValueMap?: Map<EnumKey, EnumValue>;\n _lcValueKeyMap?: Map<EnumValue, EnumKey>;\n _lcKeyValueMap?: Map<EnumKey, EnumValue>;\n _valueLabelMap?: Map<EnumValue, Labels>;\n _values?: EnumValue[];\n _entries?: [EnumKey, EnumValue][];\n}\n\nconst CACHED_ENUMS = new WeakMap<GenericEnum, Cache>();\n\n/**\n * Wraps an enum or enum-like object to provide methods for interacting with it.\n *\n * Uses a WeakMap and lazy instantiation to cache the enum's keys, values, and labels\n * for fast performance while keeping memory footprint small.\n *\n * @param enm - an enum or enum like object\n * @returns a Superenum object that provides methods to interact with the enum\n */\nfunction Enum<K extends string, V extends string | number, T extends ObjectEnum<K, V>>(\n enm: T,\n): Superenum<K, V, T> {\n let _cache: Cache = CACHED_ENUMS.get(enm) as Cache;\n\n // Get the enum as a generic object\n const enmAny = enm as unknown as Record<string, EnumValue>;\n\n if (!_cache) {\n // Get iteration keys from the enum object (ignore reverse mapped integers)\n const enmKeys: EnumKey[] = [];\n for (const key in enm) {\n const nkey = Number(key);\n const isReverseKey = !isNaN(nkey) && enmAny[enmAny[nkey]] === nkey;\n\n if (!isReverseKey) {\n enmKeys.push(key);\n }\n }\n\n const newCache: Cache = {\n _keys: enmKeys,\n _valueKeyMap: new Map(),\n } as Cache;\n\n // Fill keyValueMap and lcKeyValueMap, valueKeyMap and lcValueKeyMap\n for (const key of newCache._keys) {\n const value = enmAny[key];\n newCache._valueKeyMap.set(value, key);\n }\n\n CACHED_ENUMS.set(enm, newCache);\n _cache = newCache;\n }\n\n function createKeyValueMap(): Map<EnumKey, EnumValue> {\n const newMap = new Map<EnumKey, EnumValue>();\n for (const key of _cache._keys) {\n const value = enmAny[key] as EnumValue;\n newMap.set(key, value);\n }\n _cache._keyValueMap = newMap;\n return newMap;\n }\n\n function createLowerCaseValueKeyMap(): Map<EnumValue, EnumKey> {\n const newMap = new Map<EnumValue, EnumKey>();\n for (const key of _cache._keys) {\n const value = enmAny[key];\n const lcValue = typeof value === 'string' ? value.toLowerCase() : value;\n newMap.set(lcValue, key);\n }\n _cache._lcValueKeyMap = newMap;\n\n return newMap;\n }\n\n function createLowerCaseKeyValueMap(): Map<EnumKey, EnumValue> {\n const newMap = new Map<EnumKey, EnumValue>();\n for (const key of _cache._keys) {\n const value = enmAny[key];\n newMap.set(key.toLowerCase(), value as EnumValue);\n }\n _cache._lcKeyValueMap = newMap;\n return newMap;\n }\n\n function createValueLabelMap(): Map<EnumValue, Labels> {\n const newMap = new Map<EnumValue, Labels>();\n _cache._valueLabelMap = newMap;\n return newMap;\n }\n\n function createValues() {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n _cache._values = _cache._keys.map((k) => keyValueMap.get(k)!);\n return _cache._values;\n }\n\n function createEntries() {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n _cache._entries = _cache._keys.map((k) => [k, keyValueMap.get(k)!]);\n return _cache._entries;\n }\n\n function fromValue(value: EnumValue, options?: FromValueOptions) {\n if (options?.ignoreCase && typeof value === 'string') {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap();\n const key = lcValueKeyMap.get(value.toLowerCase());\n if (!key) return undefined;\n return keyValueMap.get(key);\n }\n if (!_cache._valueKeyMap.has(value)) return undefined;\n return value;\n }\n\n function fromKey(key: EnumKey, options?: FromKeyOptions) {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n if (options?.ignoreCase && typeof key === 'string') {\n const lcKeyValueMap = _cache._lcKeyValueMap ?? createLowerCaseKeyValueMap();\n return lcKeyValueMap.get(key.toLowerCase());\n }\n return keyValueMap.get(`${key}`);\n }\n\n function keyFromValue(value: EnumValue, options?: KeyFromValueOptions) {\n if (options?.ignoreCase && typeof value === 'string') {\n const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap();\n return lcValueKeyMap.get(value.toLowerCase());\n }\n return _cache._valueKeyMap.get(value);\n }\n\n function hasKey(key: EnumKey, options?: HasKeyOptions) {\n return fromKey(key, options) != null;\n }\n\n function hasValue(value: EnumValue, options?: HasValueOptions) {\n return fromValue(value, options) != null;\n }\n\n function keys() {\n return _cache._keys;\n }\n\n function values() {\n return _cache._values ?? createValues();\n }\n\n function entries() {\n return _cache._entries ?? createEntries();\n }\n\n function* valueIterator() {\n for (const v of values()) {\n yield v;\n }\n }\n\n function setAllLabels(allLabels: { [key: EnumValue]: Labels }): void {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n for (const [v, labels] of Object.entries(allLabels)) {\n const value = fromValue(v);\n if (value != null) {\n valueLabelMap.set(value, labels);\n }\n }\n }\n\n function setLabels(value: EnumValue, labels: Labels): void {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n valueLabelMap.set(value, labels);\n }\n\n function getLabels(value: EnumValue): Labels {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n return valueLabelMap.get(value) ?? {};\n }\n\n function getLabel(value: EnumValue, locale?: string): string {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n const labels = valueLabelMap.get(value) ?? {};\n if (!locale) {\n for (const label of Object.values(labels)) {\n return label ?? `${value}`;\n }\n }\n return labels[locale as string] ?? `${value}`;\n }\n\n return {\n fromValue,\n fromKey,\n keyFromValue,\n hasKey,\n hasValue,\n keys: () => keys(),\n values: () => values(),\n entries: () => entries(),\n [Symbol.iterator]: valueIterator,\n setAllLabels,\n setLabels,\n getLabels,\n getLabel,\n } as unknown as Superenum<K, V, T>;\n}\n\nEnum.fromArray = <KV extends Readonly<EnumKey>, T extends ArrayEnum<KV>>(\n enumeration: T,\n): ArrayEnumToObjectEnum<T> => {\n let arr: ArrayEnum<KV> = enumeration;\n if (!Array.isArray(arr)) arr = [];\n\n const enm = arr.reduce((acc, v) => {\n acc[v] = v;\n return acc;\n }, {});\n\n return enm as ArrayEnumToObjectEnum<T>;\n};\n\nexport type EnumFunc = typeof Enum;\n\nexport { Enum };\n"],"mappings":"6bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,ICuOA,IAAMC,EAAe,IAAI,QAWzB,SAASC,EACPC,EACoB,CACpB,IAAIC,EAAgBH,EAAa,IAAIE,CAAG,EAGlCE,EAASF,EAEf,GAAI,CAACC,EAAQ,CAEX,IAAME,EAAqB,CAAC,EAC5B,QAAWC,KAAOJ,EAAK,CACrB,IAAMK,EAAO,OAAOD,CAAG,EACF,CAAC,MAAMC,CAAI,GAAKH,EAAOA,EAAOG,CAAI,CAAC,IAAMA,GAG5DF,EAAQ,KAAKC,CAAG,CAEpB,CAEA,IAAME,EAAkB,CACtB,MAAOH,EACP,aAAc,IAAI,GACpB,EAGA,QAAWC,KAAOE,EAAS,MAAO,CAChC,IAAMC,EAAQL,EAAOE,CAAG,EACxBE,EAAS,aAAa,IAAIC,EAAOH,CAAG,CACtC,CAEAN,EAAa,IAAIE,EAAKM,CAAQ,EAC9BL,EAASK,CACX,CAEA,SAASE,GAA6C,CACpD,IAAMC,EAAS,IAAI,IACnB,QAAWL,KAAOH,EAAO,MAAO,CAC9B,IAAMM,EAAQL,EAAOE,CAAG,EACxBK,EAAO,IAAIL,EAAKG,CAAK,CACvB,CACA,OAAAN,EAAO,aAAeQ,EACfA,CACT,CAEA,SAASC,GAAsD,CAC7D,IAAMD,EAAS,IAAI,IACnB,QAAWL,KAAOH,EAA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S","Enum","enm","_cache","enmAny","enmKeys","key","nkey","newCache","value","createKeyValueMap","newMap","createLowerCaseValueKeyMap","lcValue","createLowerCaseKeyValueMap","createValueLabelMap","createValues","_a","keyValueMap","k","createEntries","fromValue","options","_b","fromKey","keyFromValue","hasKey","hasValue","keys","values","entries","valueIterator","v","setAllLabels","allLabels","valueLabelMap","labels","setLabels","getLabels","getLabel","locale","_c","label","enumeration","arr","acc"]} |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / Enum | ||
| # Function: Enum() | ||
| > **Enum**\<`K`, `V`, `T`\>(`enm`): [`Superenum`](../interfaces/Superenum.md)\<`K`, `V`, `T`\> | ||
| Defined in: [superenum.ts:243](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L243) | ||
| Wraps an enum or enum-like object to provide methods for interacting with it. | ||
| Uses a WeakMap and lazy instantiation to cache the enum's keys, values, and labels | ||
| for fast performance while keeping memory footprint small. | ||
| ## Type Parameters | ||
| ### K | ||
| `K` *extends* `string` | ||
| ### V | ||
| `V` *extends* `string` \| `number` | ||
| ### T | ||
| `T` *extends* `ObjectEnum`\<`K`, `V`\> | ||
| ## Parameters | ||
| ### enm | ||
| `T` | ||
| an enum or enum like object | ||
| ## Returns | ||
| [`Superenum`](../interfaces/Superenum.md)\<`K`, `V`, `T`\> | ||
| a Superenum object that provides methods to interact with the enum |
| [**@ncoderz/superenum**](README.md) | ||
| *** | ||
| # @ncoderz/superenum | ||
| ## Interfaces | ||
| - [FromValueOptions](interfaces/FromValueOptions.md) | ||
| - [FromKeyOptions](interfaces/FromKeyOptions.md) | ||
| - [KeyFromValueOptions](interfaces/KeyFromValueOptions.md) | ||
| - [HasKeyOptions](interfaces/HasKeyOptions.md) | ||
| - [HasValueOptions](interfaces/HasValueOptions.md) | ||
| - [Labels](interfaces/Labels.md) | ||
| - [Superenum](interfaces/Superenum.md) | ||
| ## Type Aliases | ||
| - [EnumType](type-aliases/EnumType.md) | ||
| - [ArrayEnum](type-aliases/ArrayEnum.md) | ||
| - [ArrayEnumToObjectEnum](type-aliases/ArrayEnumToObjectEnum.md) | ||
| - [EnumFunc](type-aliases/EnumFunc.md) | ||
| ## Functions | ||
| - [Enum](functions/Enum.md) |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / FromKeyOptions | ||
| # Interface: FromKeyOptions | ||
| Defined in: [superenum.ts:19](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L19) | ||
| Options for the [Superenum.fromKey](Superenum.md#fromkey) function | ||
| ## Properties | ||
| ### ignoreCase? | ||
| > `optional` **ignoreCase**: `boolean` | ||
| Defined in: [superenum.ts:23](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L23) | ||
| Ignore case when getting the enum value from the key |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / FromValueOptions | ||
| # Interface: FromValueOptions | ||
| Defined in: [superenum.ts:9](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L9) | ||
| Options for the [Superenum.fromValue](Superenum.md#fromvalue) function | ||
| ## Properties | ||
| ### ignoreCase? | ||
| > `optional` **ignoreCase**: `boolean` | ||
| Defined in: [superenum.ts:13](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L13) | ||
| Ignore case when validating the enum value |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / HasKeyOptions | ||
| # Interface: HasKeyOptions | ||
| Defined in: [superenum.ts:39](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L39) | ||
| Options for the [Superenum.hasKey](Superenum.md#haskey) function | ||
| ## Properties | ||
| ### ignoreCase? | ||
| > `optional` **ignoreCase**: `boolean` | ||
| Defined in: [superenum.ts:43](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L43) | ||
| Ignore case when getting the enum key from the value |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / HasValueOptions | ||
| # Interface: HasValueOptions | ||
| Defined in: [superenum.ts:49](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L49) | ||
| Options for the [Superenum.hasValue](Superenum.md#hasvalue) function | ||
| ## Properties | ||
| ### ignoreCase? | ||
| > `optional` **ignoreCase**: `boolean` | ||
| Defined in: [superenum.ts:53](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L53) | ||
| Ignore case when getting the enum key from the value |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / KeyFromValueOptions | ||
| # Interface: KeyFromValueOptions | ||
| Defined in: [superenum.ts:29](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L29) | ||
| Options for the [Superenum.keyFromValue](Superenum.md#keyfromvalue) function | ||
| ## Properties | ||
| ### ignoreCase? | ||
| > `optional` **ignoreCase**: `boolean` | ||
| Defined in: [superenum.ts:33](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L33) | ||
| Ignore case when getting the enum key from the value |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / Labels | ||
| # Interface: Labels | ||
| Defined in: [superenum.ts:59](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L59) | ||
| i18n labels for enum values. | ||
| ## Indexable | ||
| \[`key`: `string`\]: `string` |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / Superenum | ||
| # Interface: Superenum\<K, V, T\> | ||
| Defined in: [superenum.ts:75](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L75) | ||
| ## Type Parameters | ||
| ### K | ||
| `K` *extends* `EnumKey` = `EnumKey` | ||
| ### V | ||
| `V` *extends* `EnumValue` = `EnumValue` | ||
| ### T | ||
| `T` *extends* `ObjectEnum`\<`K`, `V`\> = `ObjectEnum`\<`K`, `V`\> | ||
| ## Methods | ||
| ### fromValue() | ||
| > **fromValue**(`value`, `options?`): `undefined` \| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| Defined in: [superenum.ts:93](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L93) | ||
| Validate a possible enum value, returning the enum value if valid, otherwise undefined. | ||
| Since an enum value is just the value, then all this function does is check to see if the value exists on the enum, and if | ||
| so returns it cast to the enum type, otherwise it returns undefined. | ||
| Note: If the enum has duplicate values when lower-cased and | ||
| [FromValueOptions.ignoreCase](FromValueOptions.md#ignorecase) is true, the data returned when when values clash will be indeterminate. | ||
| #### Parameters | ||
| ##### value | ||
| `unknown` | ||
| the enum value to validate | ||
| ##### options? | ||
| [`FromValueOptions`](FromValueOptions.md) | ||
| options for the function | ||
| #### Returns | ||
| `undefined` \| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| the enum value, or undefined if the value cannot be matched to the enum | ||
| *** | ||
| ### fromKey() | ||
| > **fromKey**(`key`, `options?`): `undefined` \| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| Defined in: [superenum.ts:105](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L105) | ||
| Get an enum value from its key, returning the value if key valid, otherwise undefined. | ||
| Note: If the enum has duplicate keys when lower-cased and | ||
| [FromKeyOptions.ignoreCase](FromKeyOptions.md#ignorecase) is true, the data returned when when keys clash will be indeterminate. | ||
| #### Parameters | ||
| ##### key | ||
| the enum key to convert to enum value | ||
| `undefined` | `null` | `string` | `number` | ||
| ##### options? | ||
| [`FromKeyOptions`](FromKeyOptions.md) | ||
| options for the function | ||
| #### Returns | ||
| `undefined` \| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| the enum represented by the key, or undefined if the key cannot be matched to the enum | ||
| *** | ||
| ### keyFromValue() | ||
| > **keyFromValue**(`value`, `options?`): `undefined` \| `string` | ||
| Defined in: [superenum.ts:120](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L120) | ||
| Get an enum key from its value, returning the key if value valid, otherwise undefined. | ||
| Note: If the enum has duplicate values when lower-cased and | ||
| [FromValueOptions.ignoreCase](FromValueOptions.md#ignorecase) is true, the data returned when when values clash will be indeterminate. | ||
| #### Parameters | ||
| ##### value | ||
| `unknown` | ||
| the enum value to convert to enum key | ||
| ##### options? | ||
| [`KeyFromValueOptions`](KeyFromValueOptions.md) | ||
| options for the function | ||
| #### Returns | ||
| `undefined` \| `string` | ||
| the enum key represented by the value, or undefined if the value cannot be matched to the enum | ||
| *** | ||
| ### hasValue() | ||
| > **hasValue**(`value`, `options?`): `boolean` | ||
| Defined in: [superenum.ts:135](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L135) | ||
| Check if an enum has a value, returning true if yes, otherwise false. | ||
| Note: If the enum has duplicate values (or duplicate values when lower-cased if | ||
| [HasValueOptions.ignoreCase](HasValueOptions.md#ignorecase) is true), the data returned when when values clash will be indeterminate. | ||
| #### Parameters | ||
| ##### value | ||
| the enum value to check | ||
| `undefined` | `null` | [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| ##### options? | ||
| [`HasValueOptions`](HasValueOptions.md) | ||
| options for the function | ||
| #### Returns | ||
| `boolean` | ||
| true if the enum has the value, otherwise false | ||
| *** | ||
| ### hasKey() | ||
| > **hasKey**(`key`, `options?`): `boolean` | ||
| Defined in: [superenum.ts:147](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L147) | ||
| Check if an enum has a key, returning true if yes, otherwise false. | ||
| Note: If the enum has duplicate keys when lower-cased and | ||
| [FromKeyOptions.ignoreCase](FromKeyOptions.md#ignorecase) is true, the data returned when when keys clash will be indeterminate. | ||
| #### Parameters | ||
| ##### key | ||
| the enum key to check | ||
| `undefined` | `null` | `string` | ||
| ##### options? | ||
| [`HasKeyOptions`](HasKeyOptions.md) | ||
| options for the function | ||
| #### Returns | ||
| `boolean` | ||
| true if the enum has the key, otherwise false | ||
| *** | ||
| ### values() | ||
| > **values**(): readonly [`EnumType`](../type-aliases/EnumType.md)\<`T`\>[] | ||
| Defined in: [superenum.ts:154](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L154) | ||
| Get an array of the enum values. | ||
| #### Returns | ||
| readonly [`EnumType`](../type-aliases/EnumType.md)\<`T`\>[] | ||
| iterator over the enum values | ||
| *** | ||
| ### keys() | ||
| > **keys**(): readonly keyof `T`[] | ||
| Defined in: [superenum.ts:161](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L161) | ||
| Get an array of the enum keys. | ||
| #### Returns | ||
| readonly keyof `T`[] | ||
| iterator over the enum values | ||
| *** | ||
| ### entries() | ||
| > **entries**(): readonly \[keyof `T`, [`EnumType`](../type-aliases/EnumType.md)\<`T`\>\][] | ||
| Defined in: [superenum.ts:168](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L168) | ||
| Get an array of the enum entries. | ||
| #### Returns | ||
| readonly \[keyof `T`, [`EnumType`](../type-aliases/EnumType.md)\<`T`\>\][] | ||
| iterator over the enum values | ||
| *** | ||
| ### \[iterator\]() | ||
| > **\[iterator\]**(): `IterableIterator`\<[`EnumType`](../type-aliases/EnumType.md)\<`T`\>\> | ||
| Defined in: [superenum.ts:175](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L175) | ||
| An iterator that iterates the enum values. | ||
| #### Returns | ||
| `IterableIterator`\<[`EnumType`](../type-aliases/EnumType.md)\<`T`\>\> | ||
| iterator over the enum values | ||
| *** | ||
| ### setAllLabels() | ||
| > **setAllLabels**(`allLabels`): `void` | ||
| Defined in: [superenum.ts:182](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L182) | ||
| Set i18n labels for all enum values. | ||
| #### Parameters | ||
| ##### allLabels | ||
| an object containing i18n labels for each enum value | ||
| #### Returns | ||
| `void` | ||
| *** | ||
| ### setLabels() | ||
| > **setLabels**(`value`, `labels`): `void` | ||
| Defined in: [superenum.ts:190](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L190) | ||
| Set i18n labels for a specific enum value. | ||
| #### Parameters | ||
| ##### value | ||
| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| the enum value to set i18n labels for | ||
| ##### labels | ||
| [`Labels`](Labels.md) | ||
| an object containing i18n labels for the enum value | ||
| #### Returns | ||
| `void` | ||
| *** | ||
| ### getLabels() | ||
| > **getLabels**(`value`): [`Labels`](Labels.md) | ||
| Defined in: [superenum.ts:198](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L198) | ||
| Get i18n labels for a specific enum value. | ||
| #### Parameters | ||
| ##### value | ||
| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| the enum value to get i18n labels for | ||
| #### Returns | ||
| [`Labels`](Labels.md) | ||
| an object containing i18n labels for the enum value | ||
| *** | ||
| ### getLabel() | ||
| > **getLabel**(`value`, `locale?`): `string` | ||
| Defined in: [superenum.ts:210](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L210) | ||
| Get a label for a specific enum value in a specific locale. | ||
| If no locale is provided, it will return the first label that was set. | ||
| If no label is found for the value, it will return the value as a string. | ||
| #### Parameters | ||
| ##### value | ||
| [`EnumType`](../type-aliases/EnumType.md)\<`T`\> | ||
| the enum value to get the label for | ||
| ##### locale? | ||
| `string` | ||
| the locale to get the label for | ||
| #### Returns | ||
| `string` | ||
| the label for the enum value in the specified locale |
| **@ncoderz/superenum** | ||
| *** | ||
| Simple, typesafe enums in TypeScript, fully compatible with standard JavaScript. | ||
| ## API | ||
| * [superenum(objEnum)](interfaces/Superenum.md) | ||
| * Superenum.fromObject superenum.fromObject(objEnum) | ||
| * Superenum.fromArray superenum.fromArray(arrEnum) | ||
| * EnumExtensions.fromValue \[enum\].fromValue(value, options?) | ||
| * EnumExtensions.fromKey \[enum\].fromKey(key, options?) | ||
| * EnumExtensions.keyFromValue \[enum\].keyFromValue(key, options?) | ||
| * EnumExtensions.setMetadata \[enum\].setMetadata(value, metadata, options?) | ||
| * EnumExtensions.getMetadata \[enum\].getMetadata(value, options?) | ||
| * EnumExtensions.values \[enum\].values() | ||
| * EnumExtensions.keys \[enum\].keys() | ||
| * EnumExtensions.entries \[enum\].entries() | ||
| ## License | ||
| This open source software is licenced under the [BSD-2-Clause licence](https://opensource.org/licenses/BSD-2-Clause). |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / ArrayEnum | ||
| # Type Alias: ArrayEnum\<KV\> | ||
| > **ArrayEnum**\<`KV`\> = `ReadonlyArray`\<`KV`\> | ||
| Defined in: [superenum.ts:66](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L66) | ||
| Array Enum declaration | ||
| ## Type Parameters | ||
| ### KV | ||
| `KV` *extends* `EnumKey` |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / ArrayEnumToObjectEnum | ||
| # Type Alias: ArrayEnumToObjectEnum\<T\> | ||
| > **ArrayEnumToObjectEnum**\<`T`\> = `{ [K in T[number]]: K }` | ||
| Defined in: [superenum.ts:71](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L71) | ||
| Convert an ArrayEnum type to an ObjectEnum | ||
| ## Type Parameters | ||
| ### T | ||
| `T` *extends* `ReadonlyArray`\<`string`\> |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / EnumFunc | ||
| # Type Alias: EnumFunc | ||
| > **EnumFunc** = *typeof* [`Enum`](../functions/Enum.md) | ||
| Defined in: [superenum.ts:445](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L445) |
| [**@ncoderz/superenum**](../README.md) | ||
| *** | ||
| [@ncoderz/superenum](../globals.md) / EnumType | ||
| # Type Alias: EnumType\<T\> | ||
| > **EnumType**\<`T`\> = `T`\[keyof `T`\] | ||
| Defined in: [superenum.ts:4](https://github.com/ncoderz/superenum/blob/08c1c2419d89a58d6deeaad343b246571a3c3674/src/superenum.ts#L4) | ||
| Create an enum type from an enum like object or array. | ||
| ## Type Parameters | ||
| ### T | ||
| `T` |
+197
| "use strict"; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| var __export = (target, all) => { | ||
| for (var name in all) | ||
| __defProp(target, name, { get: all[name], enumerable: true }); | ||
| }; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") { | ||
| for (let key of __getOwnPropNames(from)) | ||
| if (!__hasOwnProp.call(to, key) && key !== except) | ||
| __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
| } | ||
| return to; | ||
| }; | ||
| var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
| // src/index.ts | ||
| var index_exports = {}; | ||
| __export(index_exports, { | ||
| Enum: () => Enum | ||
| }); | ||
| module.exports = __toCommonJS(index_exports); | ||
| // src/superenum.ts | ||
| var CACHED_ENUMS = /* @__PURE__ */ new WeakMap(); | ||
| function Enum(enm) { | ||
| let _cache = CACHED_ENUMS.get(enm); | ||
| const enmAny = enm; | ||
| if (!_cache) { | ||
| const enmKeys = []; | ||
| for (const key in enm) { | ||
| const nkey = Number(key); | ||
| const isReverseKey = !isNaN(nkey) && enmAny[enmAny[nkey]] === nkey; | ||
| if (!isReverseKey) { | ||
| enmKeys.push(key); | ||
| } | ||
| } | ||
| const newCache = { | ||
| _keys: enmKeys, | ||
| _valueKeyMap: /* @__PURE__ */ new Map() | ||
| }; | ||
| for (const key of newCache._keys) { | ||
| const value = enmAny[key]; | ||
| newCache._valueKeyMap.set(value, key); | ||
| } | ||
| CACHED_ENUMS.set(enm, newCache); | ||
| _cache = newCache; | ||
| } | ||
| function createKeyValueMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| for (const key of _cache._keys) { | ||
| const value = enmAny[key]; | ||
| newMap.set(key, value); | ||
| } | ||
| _cache._keyValueMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createLowerCaseValueKeyMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| for (const key of _cache._keys) { | ||
| const value = enmAny[key]; | ||
| const lcValue = typeof value === "string" ? value.toLowerCase() : value; | ||
| newMap.set(lcValue, key); | ||
| } | ||
| _cache._lcValueKeyMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createLowerCaseKeyValueMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| for (const key of _cache._keys) { | ||
| const value = enmAny[key]; | ||
| newMap.set(key.toLowerCase(), value); | ||
| } | ||
| _cache._lcKeyValueMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createValueLabelMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| _cache._valueLabelMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createValues() { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| _cache._values = _cache._keys.map((k) => keyValueMap.get(k)); | ||
| return _cache._values; | ||
| } | ||
| function createEntries() { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| _cache._entries = _cache._keys.map((k) => [k, keyValueMap.get(k)]); | ||
| return _cache._entries; | ||
| } | ||
| function fromValue(value, options) { | ||
| if (options?.ignoreCase && typeof value === "string") { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap(); | ||
| const key = lcValueKeyMap.get(value.toLowerCase()); | ||
| if (!key) return void 0; | ||
| return keyValueMap.get(key); | ||
| } | ||
| if (!_cache._valueKeyMap.has(value)) return void 0; | ||
| return value; | ||
| } | ||
| function fromKey(key, options) { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| if (options?.ignoreCase && typeof key === "string") { | ||
| const lcKeyValueMap = _cache._lcKeyValueMap ?? createLowerCaseKeyValueMap(); | ||
| return lcKeyValueMap.get(key.toLowerCase()); | ||
| } | ||
| return keyValueMap.get(`${key}`); | ||
| } | ||
| function keyFromValue(value, options) { | ||
| if (options?.ignoreCase && typeof value === "string") { | ||
| const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap(); | ||
| return lcValueKeyMap.get(value.toLowerCase()); | ||
| } | ||
| return _cache._valueKeyMap.get(value); | ||
| } | ||
| function hasKey(key, options) { | ||
| return fromKey(key, options) != null; | ||
| } | ||
| function hasValue(value, options) { | ||
| return fromValue(value, options) != null; | ||
| } | ||
| function keys() { | ||
| return _cache._keys; | ||
| } | ||
| function values() { | ||
| return _cache._values ?? createValues(); | ||
| } | ||
| function entries() { | ||
| return _cache._entries ?? createEntries(); | ||
| } | ||
| function* valueIterator() { | ||
| for (const v of values()) { | ||
| yield v; | ||
| } | ||
| } | ||
| function setAllLabels(allLabels) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| for (const [v, labels] of Object.entries(allLabels)) { | ||
| const value = fromValue(v); | ||
| if (value != null) { | ||
| valueLabelMap.set(value, labels); | ||
| } | ||
| } | ||
| } | ||
| function setLabels(value, labels) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| valueLabelMap.set(value, labels); | ||
| } | ||
| function getLabels(value) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| return valueLabelMap.get(value) ?? {}; | ||
| } | ||
| function getLabel(value, locale) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| const labels = valueLabelMap.get(value) ?? {}; | ||
| if (!locale) { | ||
| for (const label of Object.values(labels)) { | ||
| return label ?? `${value}`; | ||
| } | ||
| } | ||
| return labels[locale] ?? `${value}`; | ||
| } | ||
| return { | ||
| fromValue, | ||
| fromKey, | ||
| keyFromValue, | ||
| hasKey, | ||
| hasValue, | ||
| keys: () => keys(), | ||
| values: () => values(), | ||
| entries: () => entries(), | ||
| [Symbol.iterator]: valueIterator, | ||
| setAllLabels, | ||
| setLabels, | ||
| getLabels, | ||
| getLabel | ||
| }; | ||
| } | ||
| Enum.fromArray = (enumeration) => { | ||
| let arr = enumeration; | ||
| if (!Array.isArray(arr)) arr = []; | ||
| const enm = arr.reduce((acc, v) => { | ||
| acc[v] = v; | ||
| return acc; | ||
| }, {}); | ||
| return enm; | ||
| }; | ||
| // Annotate the CommonJS export names for ESM import in node: | ||
| 0 && (module.exports = { | ||
| Enum | ||
| }); | ||
| //# sourceMappingURL=index.cjs.map |
| {"version":3,"sources":["../src/index.ts","../src/superenum.ts"],"sourcesContent":["export {\n Enum,\n type EnumFunc,\n type EnumType,\n type FromKeyOptions,\n type FromValueOptions,\n type HasKeyOptions,\n type HasValueOptions,\n type KeyFromValueOptions,\n type Labels,\n} from './superenum';\n","/**\n * Create an enum type from an enum like object or array.\n */\nexport type EnumType<T> = T[keyof T];\n\n/**\n * Options for the {@link Superenum.fromValue} function\n */\nexport interface FromValueOptions {\n /**\n * Ignore case when validating the enum value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.fromKey} function\n */\nexport interface FromKeyOptions {\n /**\n * Ignore case when getting the enum value from the key\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.keyFromValue} function\n */\nexport interface KeyFromValueOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.hasKey} function\n */\nexport interface HasKeyOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.hasValue} function\n */\nexport interface HasValueOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * i18n labels for enum values.\n */\nexport interface Labels {\n [key: string]: string;\n}\n\n/**\n * Array Enum declaration\n */\nexport type ArrayEnum<KV extends EnumKey> = ReadonlyArray<KV>;\n\n/**\n * Convert an ArrayEnum type to an ObjectEnum\n */\nexport type ArrayEnumToObjectEnum<T extends ReadonlyArray<string>> = {\n [K in T[number]]: K;\n};\n\nexport interface Superenum<\n K extends EnumKey = EnumKey,\n V extends EnumValue = EnumValue,\n T extends ObjectEnum<K, V> = ObjectEnum<K, V>,\n> {\n /**\n * Validate a possible enum value, returning the enum value if valid, otherwise undefined.\n *\n * Since an enum value is just the value, then all this function does is check to see if the value exists on the enum, and if\n * so returns it cast to the enum type, otherwise it returns undefined.\n *\n * Note: If the enum has duplicate values when lower-cased and\n * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to validate\n * @param options - options for the function\n * @returns the enum value, or undefined if the value cannot be matched to the enum\n */\n fromValue(value: unknown | null | undefined, options?: FromValueOptions): EnumType<T> | undefined;\n\n /**\n * Get an enum value from its key, returning the value if key valid, otherwise undefined.\n *\n * Note: If the enum has duplicate keys when lower-cased and\n * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.\n *\n * @param key - the enum key to convert to enum value\n * @param options - options for the function\n * @returns the enum represented by the key, or undefined if the key cannot be matched to the enum\n */\n fromKey(\n key: EnumKey | number | null | undefined,\n options?: FromKeyOptions,\n ): EnumType<T> | undefined;\n\n /**\n * Get an enum key from its value, returning the key if value valid, otherwise undefined.\n *\n * Note: If the enum has duplicate values when lower-cased and\n * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to convert to enum key\n * @param options - options for the function\n * @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum\n */\n keyFromValue(\n value: unknown | null | undefined,\n options?: KeyFromValueOptions,\n ): string | undefined;\n\n /**\n * Check if an enum has a value, returning true if yes, otherwise false.\n *\n * Note: If the enum has duplicate values (or duplicate values when lower-cased if\n * {@link HasValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to check\n * @param options - options for the function\n * @returns true if the enum has the value, otherwise false\n */\n hasValue(value: EnumType<T> | null | undefined, options?: HasValueOptions): boolean;\n\n /**\n * Check if an enum has a key, returning true if yes, otherwise false.\n *\n * Note: If the enum has duplicate keys when lower-cased and\n * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.\n *\n * @param key - the enum key to check\n * @param options - options for the function\n * @returns true if the enum has the key, otherwise false\n */\n hasKey(key: EnumKey | null | undefined, options?: HasKeyOptions): boolean;\n\n /**\n * Get an array of the enum values.\n *\n * @returns iterator over the enum values\n */\n values(): readonly EnumType<T>[];\n\n /**\n * Get an array of the enum keys.\n *\n * @returns iterator over the enum values\n */\n keys(): readonly ExtractEnumKey<K, V, T>[];\n\n /**\n * Get an array of the enum entries.\n *\n * @returns iterator over the enum values\n */\n entries(): readonly [ExtractEnumKey<K, V, T>, EnumType<T>][];\n\n /**\n * An iterator that iterates the enum values.\n *\n * @returns iterator over the enum values\n */\n [Symbol.iterator](): IterableIterator<EnumType<T>>;\n\n /**\n * Set i18n labels for all enum values.\n *\n * @param allLabels - an object containing i18n labels for each enum value\n */\n setAllLabels(allLabels: { [key: EnumValue]: Labels }): void;\n\n /**\n * Set i18n labels for a specific enum value.\n *\n * @param value - the enum value to set i18n labels for\n * @param labels - an object containing i18n labels for the enum value\n */\n setLabels(value: EnumType<T>, labels: Labels): void;\n\n /**\n * Get i18n labels for a specific enum value.\n *\n * @param value - the enum value to get i18n labels for\n * @returns an object containing i18n labels for the enum value\n */\n getLabels(value: EnumType<T>): Labels;\n\n /**\n * Get a label for a specific enum value in a specific locale.\n *\n * If no locale is provided, it will return the first label that was set.\n * If no label is found for the value, it will return the value as a string.\n *\n * @param value - the enum value to get the label for\n * @param locale - the locale to get the label for\n * @returns the label for the enum value in the specified locale\n */\n getLabel(value: EnumType<T>, locale?: string): string;\n}\n\ntype EnumKey = string;\ntype EnumValue = string | number;\ntype ExtractEnumKey<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>> = keyof T;\n\ntype GenericEnum = Readonly<Record<EnumKey, EnumValue>>;\n\ntype ObjectEnum<K extends EnumKey, V extends EnumValue> = { [key in K]: V };\n\ninterface Cache {\n _keys: EnumKey[];\n _valueKeyMap: Map<EnumValue, EnumKey>;\n _keyValueMap?: Map<EnumKey, EnumValue>;\n _lcValueKeyMap?: Map<EnumValue, EnumKey>;\n _lcKeyValueMap?: Map<EnumKey, EnumValue>;\n _valueLabelMap?: Map<EnumValue, Labels>;\n _values?: EnumValue[];\n _entries?: [EnumKey, EnumValue][];\n}\n\nconst CACHED_ENUMS = new WeakMap<GenericEnum, Cache>();\n\n/**\n * Wraps an enum or enum-like object to provide methods for interacting with it.\n *\n * Uses a WeakMap and lazy instantiation to cache the enum's keys, values, and labels\n * for fast performance while keeping memory footprint small.\n *\n * @param enm - an enum or enum like object\n * @returns a Superenum object that provides methods to interact with the enum\n */\nfunction Enum<K extends string, V extends string | number, T extends ObjectEnum<K, V>>(\n enm: T,\n): Superenum<K, V, T> {\n let _cache: Cache = CACHED_ENUMS.get(enm) as Cache;\n\n // Get the enum as a generic object\n const enmAny = enm as unknown as Record<string, EnumValue>;\n\n if (!_cache) {\n // Get iteration keys from the enum object (ignore reverse mapped integers)\n const enmKeys: EnumKey[] = [];\n for (const key in enm) {\n const nkey = Number(key);\n const isReverseKey = !isNaN(nkey) && enmAny[enmAny[nkey]] === nkey;\n\n if (!isReverseKey) {\n enmKeys.push(key);\n }\n }\n\n const newCache: Cache = {\n _keys: enmKeys,\n _valueKeyMap: new Map(),\n } as Cache;\n\n // Fill keyValueMap and lcKeyValueMap, valueKeyMap and lcValueKeyMap\n for (const key of newCache._keys) {\n const value = enmAny[key];\n newCache._valueKeyMap.set(value, key);\n }\n\n CACHED_ENUMS.set(enm, newCache);\n _cache = newCache;\n }\n\n function createKeyValueMap(): Map<EnumKey, EnumValue> {\n const newMap = new Map<EnumKey, EnumValue>();\n for (const key of _cache._keys) {\n const value = enmAny[key] as EnumValue;\n newMap.set(key, value);\n }\n _cache._keyValueMap = newMap;\n return newMap;\n }\n\n function createLowerCaseValueKeyMap(): Map<EnumValue, EnumKey> {\n const newMap = new Map<EnumValue, EnumKey>();\n for (const key of _cache._keys) {\n const value = enmAny[key];\n const lcValue = typeof value === 'string' ? value.toLowerCase() : value;\n newMap.set(lcValue, key);\n }\n _cache._lcValueKeyMap = newMap;\n\n return newMap;\n }\n\n function createLowerCaseKeyValueMap(): Map<EnumKey, EnumValue> {\n const newMap = new Map<EnumKey, EnumValue>();\n for (const key of _cache._keys) {\n const value = enmAny[key];\n newMap.set(key.toLowerCase(), value as EnumValue);\n }\n _cache._lcKeyValueMap = newMap;\n return newMap;\n }\n\n function createValueLabelMap(): Map<EnumValue, Labels> {\n const newMap = new Map<EnumValue, Labels>();\n _cache._valueLabelMap = newMap;\n return newMap;\n }\n\n function createValues() {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n _cache._values = _cache._keys.map((k) => keyValueMap.get(k)!);\n return _cache._values;\n }\n\n function createEntries() {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n _cache._entries = _cache._keys.map((k) => [k, keyValueMap.get(k)!]);\n return _cache._entries;\n }\n\n function fromValue(value: EnumValue, options?: FromValueOptions) {\n if (options?.ignoreCase && typeof value === 'string') {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap();\n const key = lcValueKeyMap.get(value.toLowerCase());\n if (!key) return undefined;\n return keyValueMap.get(key);\n }\n if (!_cache._valueKeyMap.has(value)) return undefined;\n return value;\n }\n\n function fromKey(key: EnumKey, options?: FromKeyOptions) {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n if (options?.ignoreCase && typeof key === 'string') {\n const lcKeyValueMap = _cache._lcKeyValueMap ?? createLowerCaseKeyValueMap();\n return lcKeyValueMap.get(key.toLowerCase());\n }\n return keyValueMap.get(`${key}`);\n }\n\n function keyFromValue(value: EnumValue, options?: KeyFromValueOptions) {\n if (options?.ignoreCase && typeof value === 'string') {\n const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap();\n return lcValueKeyMap.get(value.toLowerCase());\n }\n return _cache._valueKeyMap.get(value);\n }\n\n function hasKey(key: EnumKey, options?: HasKeyOptions) {\n return fromKey(key, options) != null;\n }\n\n function hasValue(value: EnumValue, options?: HasValueOptions) {\n return fromValue(value, options) != null;\n }\n\n function keys() {\n return _cache._keys;\n }\n\n function values() {\n return _cache._values ?? createValues();\n }\n\n function entries() {\n return _cache._entries ?? createEntries();\n }\n\n function* valueIterator() {\n for (const v of values()) {\n yield v;\n }\n }\n\n function setAllLabels(allLabels: { [key: EnumValue]: Labels }): void {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n for (const [v, labels] of Object.entries(allLabels)) {\n const value = fromValue(v);\n if (value != null) {\n valueLabelMap.set(value, labels);\n }\n }\n }\n\n function setLabels(value: EnumValue, labels: Labels): void {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n valueLabelMap.set(value, labels);\n }\n\n function getLabels(value: EnumValue): Labels {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n return valueLabelMap.get(value) ?? {};\n }\n\n function getLabel(value: EnumValue, locale?: string): string {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n const labels = valueLabelMap.get(value) ?? {};\n if (!locale) {\n for (const label of Object.values(labels)) {\n return label ?? `${value}`;\n }\n }\n return labels[locale as string] ?? `${value}`;\n }\n\n return {\n fromValue,\n fromKey,\n keyFromValue,\n hasKey,\n hasValue,\n keys: () => keys(),\n values: () => values(),\n entries: () => entries(),\n [Symbol.iterator]: valueIterator,\n setAllLabels,\n setLabels,\n getLabels,\n getLabel,\n } as unknown as Superenum<K, V, T>;\n}\n\nEnum.fromArray = <KV extends Readonly<EnumKey>, T extends ArrayEnum<KV>>(\n enumeration: T,\n): ArrayEnumToObjectEnum<T> => {\n let arr: ArrayEnum<KV> = enumeration;\n if (!Array.isArray(arr)) arr = [];\n\n const enm = arr.reduce((acc, v) => {\n acc[v] = v;\n return acc;\n }, {});\n\n return enm as ArrayEnumToObjectEnum<T>;\n};\n\nexport type EnumFunc = typeof Enum;\n\nexport { Enum };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuOA,IAAM,eAAe,oBAAI,QAA4B;AAWrD,SAAS,KACP,KACoB;AACpB,MAAI,SAAgB,aAAa,IAAI,GAAG;AAGxC,QAAM,SAAS;AAEf,MAAI,CAAC,QAAQ;AAEX,UAAM,UAAqB,CAAC;AAC5B,eAAW,OAAO,KAAK;AACrB,YAAM,OAAO,OAAO,GAAG;AAC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AAA,IACrB,SAAS,MAAM,QAAQ;AAAA,IACvB,CAAC,OAAO,QAAQ,GAAG;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA,KAAK,YAAY,CACf,gBAC6B;AAC7B,MAAI,MAAqB;AACzB,MAAI,CAAC,MAAM,QAAQ,GAAG,EAAG,OAAM,CAAC;AAEhC,QAAM,MAAM,IAAI,OAAO,CAAC,KAAK,MAAM;AACjC,QAAI,CAAC,IAAI;AACT,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;","names":[]} |
+204
| /** | ||
| * Create an enum type from an enum like object or array. | ||
| */ | ||
| type EnumType<T> = T[keyof T]; | ||
| /** | ||
| * Options for the {@link Superenum.fromValue} function | ||
| */ | ||
| interface FromValueOptions { | ||
| /** | ||
| * Ignore case when validating the enum value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.fromKey} function | ||
| */ | ||
| interface FromKeyOptions { | ||
| /** | ||
| * Ignore case when getting the enum value from the key | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.keyFromValue} function | ||
| */ | ||
| interface KeyFromValueOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.hasKey} function | ||
| */ | ||
| interface HasKeyOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.hasValue} function | ||
| */ | ||
| interface HasValueOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * i18n labels for enum values. | ||
| */ | ||
| interface Labels { | ||
| [key: string]: string; | ||
| } | ||
| /** | ||
| * Array Enum declaration | ||
| */ | ||
| type ArrayEnum<KV extends EnumKey> = ReadonlyArray<KV>; | ||
| /** | ||
| * Convert an ArrayEnum type to an ObjectEnum | ||
| */ | ||
| type ArrayEnumToObjectEnum<T extends ReadonlyArray<string>> = { | ||
| [K in T[number]]: K; | ||
| }; | ||
| interface Superenum<K extends EnumKey = EnumKey, V extends EnumValue = EnumValue, T extends ObjectEnum<K, V> = ObjectEnum<K, V>> { | ||
| /** | ||
| * Validate a possible enum value, returning the enum value if valid, otherwise undefined. | ||
| * | ||
| * Since an enum value is just the value, then all this function does is check to see if the value exists on the enum, and if | ||
| * so returns it cast to the enum type, otherwise it returns undefined. | ||
| * | ||
| * Note: If the enum has duplicate values when lower-cased and | ||
| * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to validate | ||
| * @param options - options for the function | ||
| * @returns the enum value, or undefined if the value cannot be matched to the enum | ||
| */ | ||
| fromValue(value: unknown | null | undefined, options?: FromValueOptions): EnumType<T> | undefined; | ||
| /** | ||
| * Get an enum value from its key, returning the value if key valid, otherwise undefined. | ||
| * | ||
| * Note: If the enum has duplicate keys when lower-cased and | ||
| * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate. | ||
| * | ||
| * @param key - the enum key to convert to enum value | ||
| * @param options - options for the function | ||
| * @returns the enum represented by the key, or undefined if the key cannot be matched to the enum | ||
| */ | ||
| fromKey(key: EnumKey | number | null | undefined, options?: FromKeyOptions): EnumType<T> | undefined; | ||
| /** | ||
| * Get an enum key from its value, returning the key if value valid, otherwise undefined. | ||
| * | ||
| * Note: If the enum has duplicate values when lower-cased and | ||
| * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to convert to enum key | ||
| * @param options - options for the function | ||
| * @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum | ||
| */ | ||
| keyFromValue(value: unknown | null | undefined, options?: KeyFromValueOptions): string | undefined; | ||
| /** | ||
| * Check if an enum has a value, returning true if yes, otherwise false. | ||
| * | ||
| * Note: If the enum has duplicate values (or duplicate values when lower-cased if | ||
| * {@link HasValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to check | ||
| * @param options - options for the function | ||
| * @returns true if the enum has the value, otherwise false | ||
| */ | ||
| hasValue(value: EnumType<T> | null | undefined, options?: HasValueOptions): boolean; | ||
| /** | ||
| * Check if an enum has a key, returning true if yes, otherwise false. | ||
| * | ||
| * Note: If the enum has duplicate keys when lower-cased and | ||
| * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate. | ||
| * | ||
| * @param key - the enum key to check | ||
| * @param options - options for the function | ||
| * @returns true if the enum has the key, otherwise false | ||
| */ | ||
| hasKey(key: EnumKey | null | undefined, options?: HasKeyOptions): boolean; | ||
| /** | ||
| * Get an array of the enum values. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| values(): readonly EnumType<T>[]; | ||
| /** | ||
| * Get an array of the enum keys. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| keys(): readonly ExtractEnumKey<K, V, T>[]; | ||
| /** | ||
| * Get an array of the enum entries. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| entries(): readonly [ExtractEnumKey<K, V, T>, EnumType<T>][]; | ||
| /** | ||
| * An iterator that iterates the enum values. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| [Symbol.iterator](): IterableIterator<EnumType<T>>; | ||
| /** | ||
| * Set i18n labels for all enum values. | ||
| * | ||
| * @param allLabels - an object containing i18n labels for each enum value | ||
| */ | ||
| setAllLabels(allLabels: { | ||
| [key: EnumValue]: Labels; | ||
| }): void; | ||
| /** | ||
| * Set i18n labels for a specific enum value. | ||
| * | ||
| * @param value - the enum value to set i18n labels for | ||
| * @param labels - an object containing i18n labels for the enum value | ||
| */ | ||
| setLabels(value: EnumType<T>, labels: Labels): void; | ||
| /** | ||
| * Get i18n labels for a specific enum value. | ||
| * | ||
| * @param value - the enum value to get i18n labels for | ||
| * @returns an object containing i18n labels for the enum value | ||
| */ | ||
| getLabels(value: EnumType<T>): Labels; | ||
| /** | ||
| * Get a label for a specific enum value in a specific locale. | ||
| * | ||
| * If no locale is provided, it will return the first label that was set. | ||
| * If no label is found for the value, it will return the value as a string. | ||
| * | ||
| * @param value - the enum value to get the label for | ||
| * @param locale - the locale to get the label for | ||
| * @returns the label for the enum value in the specified locale | ||
| */ | ||
| getLabel(value: EnumType<T>, locale?: string): string; | ||
| } | ||
| type EnumKey = string; | ||
| type EnumValue = string | number; | ||
| type ExtractEnumKey<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>> = keyof T; | ||
| type ObjectEnum<K extends EnumKey, V extends EnumValue> = { | ||
| [key in K]: V; | ||
| }; | ||
| /** | ||
| * Wraps an enum or enum-like object to provide methods for interacting with it. | ||
| * | ||
| * Uses a WeakMap and lazy instantiation to cache the enum's keys, values, and labels | ||
| * for fast performance while keeping memory footprint small. | ||
| * | ||
| * @param enm - an enum or enum like object | ||
| * @returns a Superenum object that provides methods to interact with the enum | ||
| */ | ||
| declare function Enum<K extends string, V extends string | number, T extends ObjectEnum<K, V>>(enm: T): Superenum<K, V, T>; | ||
| declare namespace Enum { | ||
| var fromArray: <KV extends Readonly<EnumKey>, T extends ArrayEnum<KV>>(enumeration: T) => ArrayEnumToObjectEnum<T>; | ||
| } | ||
| type EnumFunc = typeof Enum; | ||
| export { Enum, type EnumFunc, type EnumType, type FromKeyOptions, type FromValueOptions, type HasKeyOptions, type HasValueOptions, type KeyFromValueOptions, type Labels }; |
+204
| /** | ||
| * Create an enum type from an enum like object or array. | ||
| */ | ||
| type EnumType<T> = T[keyof T]; | ||
| /** | ||
| * Options for the {@link Superenum.fromValue} function | ||
| */ | ||
| interface FromValueOptions { | ||
| /** | ||
| * Ignore case when validating the enum value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.fromKey} function | ||
| */ | ||
| interface FromKeyOptions { | ||
| /** | ||
| * Ignore case when getting the enum value from the key | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.keyFromValue} function | ||
| */ | ||
| interface KeyFromValueOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.hasKey} function | ||
| */ | ||
| interface HasKeyOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link Superenum.hasValue} function | ||
| */ | ||
| interface HasValueOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * i18n labels for enum values. | ||
| */ | ||
| interface Labels { | ||
| [key: string]: string; | ||
| } | ||
| /** | ||
| * Array Enum declaration | ||
| */ | ||
| type ArrayEnum<KV extends EnumKey> = ReadonlyArray<KV>; | ||
| /** | ||
| * Convert an ArrayEnum type to an ObjectEnum | ||
| */ | ||
| type ArrayEnumToObjectEnum<T extends ReadonlyArray<string>> = { | ||
| [K in T[number]]: K; | ||
| }; | ||
| interface Superenum<K extends EnumKey = EnumKey, V extends EnumValue = EnumValue, T extends ObjectEnum<K, V> = ObjectEnum<K, V>> { | ||
| /** | ||
| * Validate a possible enum value, returning the enum value if valid, otherwise undefined. | ||
| * | ||
| * Since an enum value is just the value, then all this function does is check to see if the value exists on the enum, and if | ||
| * so returns it cast to the enum type, otherwise it returns undefined. | ||
| * | ||
| * Note: If the enum has duplicate values when lower-cased and | ||
| * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to validate | ||
| * @param options - options for the function | ||
| * @returns the enum value, or undefined if the value cannot be matched to the enum | ||
| */ | ||
| fromValue(value: unknown | null | undefined, options?: FromValueOptions): EnumType<T> | undefined; | ||
| /** | ||
| * Get an enum value from its key, returning the value if key valid, otherwise undefined. | ||
| * | ||
| * Note: If the enum has duplicate keys when lower-cased and | ||
| * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate. | ||
| * | ||
| * @param key - the enum key to convert to enum value | ||
| * @param options - options for the function | ||
| * @returns the enum represented by the key, or undefined if the key cannot be matched to the enum | ||
| */ | ||
| fromKey(key: EnumKey | number | null | undefined, options?: FromKeyOptions): EnumType<T> | undefined; | ||
| /** | ||
| * Get an enum key from its value, returning the key if value valid, otherwise undefined. | ||
| * | ||
| * Note: If the enum has duplicate values when lower-cased and | ||
| * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to convert to enum key | ||
| * @param options - options for the function | ||
| * @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum | ||
| */ | ||
| keyFromValue(value: unknown | null | undefined, options?: KeyFromValueOptions): string | undefined; | ||
| /** | ||
| * Check if an enum has a value, returning true if yes, otherwise false. | ||
| * | ||
| * Note: If the enum has duplicate values (or duplicate values when lower-cased if | ||
| * {@link HasValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to check | ||
| * @param options - options for the function | ||
| * @returns true if the enum has the value, otherwise false | ||
| */ | ||
| hasValue(value: EnumType<T> | null | undefined, options?: HasValueOptions): boolean; | ||
| /** | ||
| * Check if an enum has a key, returning true if yes, otherwise false. | ||
| * | ||
| * Note: If the enum has duplicate keys when lower-cased and | ||
| * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate. | ||
| * | ||
| * @param key - the enum key to check | ||
| * @param options - options for the function | ||
| * @returns true if the enum has the key, otherwise false | ||
| */ | ||
| hasKey(key: EnumKey | null | undefined, options?: HasKeyOptions): boolean; | ||
| /** | ||
| * Get an array of the enum values. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| values(): readonly EnumType<T>[]; | ||
| /** | ||
| * Get an array of the enum keys. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| keys(): readonly ExtractEnumKey<K, V, T>[]; | ||
| /** | ||
| * Get an array of the enum entries. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| entries(): readonly [ExtractEnumKey<K, V, T>, EnumType<T>][]; | ||
| /** | ||
| * An iterator that iterates the enum values. | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| [Symbol.iterator](): IterableIterator<EnumType<T>>; | ||
| /** | ||
| * Set i18n labels for all enum values. | ||
| * | ||
| * @param allLabels - an object containing i18n labels for each enum value | ||
| */ | ||
| setAllLabels(allLabels: { | ||
| [key: EnumValue]: Labels; | ||
| }): void; | ||
| /** | ||
| * Set i18n labels for a specific enum value. | ||
| * | ||
| * @param value - the enum value to set i18n labels for | ||
| * @param labels - an object containing i18n labels for the enum value | ||
| */ | ||
| setLabels(value: EnumType<T>, labels: Labels): void; | ||
| /** | ||
| * Get i18n labels for a specific enum value. | ||
| * | ||
| * @param value - the enum value to get i18n labels for | ||
| * @returns an object containing i18n labels for the enum value | ||
| */ | ||
| getLabels(value: EnumType<T>): Labels; | ||
| /** | ||
| * Get a label for a specific enum value in a specific locale. | ||
| * | ||
| * If no locale is provided, it will return the first label that was set. | ||
| * If no label is found for the value, it will return the value as a string. | ||
| * | ||
| * @param value - the enum value to get the label for | ||
| * @param locale - the locale to get the label for | ||
| * @returns the label for the enum value in the specified locale | ||
| */ | ||
| getLabel(value: EnumType<T>, locale?: string): string; | ||
| } | ||
| type EnumKey = string; | ||
| type EnumValue = string | number; | ||
| type ExtractEnumKey<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>> = keyof T; | ||
| type ObjectEnum<K extends EnumKey, V extends EnumValue> = { | ||
| [key in K]: V; | ||
| }; | ||
| /** | ||
| * Wraps an enum or enum-like object to provide methods for interacting with it. | ||
| * | ||
| * Uses a WeakMap and lazy instantiation to cache the enum's keys, values, and labels | ||
| * for fast performance while keeping memory footprint small. | ||
| * | ||
| * @param enm - an enum or enum like object | ||
| * @returns a Superenum object that provides methods to interact with the enum | ||
| */ | ||
| declare function Enum<K extends string, V extends string | number, T extends ObjectEnum<K, V>>(enm: T): Superenum<K, V, T>; | ||
| declare namespace Enum { | ||
| var fromArray: <KV extends Readonly<EnumKey>, T extends ArrayEnum<KV>>(enumeration: T) => ArrayEnumToObjectEnum<T>; | ||
| } | ||
| type EnumFunc = typeof Enum; | ||
| export { Enum, type EnumFunc, type EnumType, type FromKeyOptions, type FromValueOptions, type HasKeyOptions, type HasValueOptions, type KeyFromValueOptions, type Labels }; |
+170
| // src/superenum.ts | ||
| var CACHED_ENUMS = /* @__PURE__ */ new WeakMap(); | ||
| function Enum(enm) { | ||
| let _cache = CACHED_ENUMS.get(enm); | ||
| const enmAny = enm; | ||
| if (!_cache) { | ||
| const enmKeys = []; | ||
| for (const key in enm) { | ||
| const nkey = Number(key); | ||
| const isReverseKey = !isNaN(nkey) && enmAny[enmAny[nkey]] === nkey; | ||
| if (!isReverseKey) { | ||
| enmKeys.push(key); | ||
| } | ||
| } | ||
| const newCache = { | ||
| _keys: enmKeys, | ||
| _valueKeyMap: /* @__PURE__ */ new Map() | ||
| }; | ||
| for (const key of newCache._keys) { | ||
| const value = enmAny[key]; | ||
| newCache._valueKeyMap.set(value, key); | ||
| } | ||
| CACHED_ENUMS.set(enm, newCache); | ||
| _cache = newCache; | ||
| } | ||
| function createKeyValueMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| for (const key of _cache._keys) { | ||
| const value = enmAny[key]; | ||
| newMap.set(key, value); | ||
| } | ||
| _cache._keyValueMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createLowerCaseValueKeyMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| for (const key of _cache._keys) { | ||
| const value = enmAny[key]; | ||
| const lcValue = typeof value === "string" ? value.toLowerCase() : value; | ||
| newMap.set(lcValue, key); | ||
| } | ||
| _cache._lcValueKeyMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createLowerCaseKeyValueMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| for (const key of _cache._keys) { | ||
| const value = enmAny[key]; | ||
| newMap.set(key.toLowerCase(), value); | ||
| } | ||
| _cache._lcKeyValueMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createValueLabelMap() { | ||
| const newMap = /* @__PURE__ */ new Map(); | ||
| _cache._valueLabelMap = newMap; | ||
| return newMap; | ||
| } | ||
| function createValues() { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| _cache._values = _cache._keys.map((k) => keyValueMap.get(k)); | ||
| return _cache._values; | ||
| } | ||
| function createEntries() { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| _cache._entries = _cache._keys.map((k) => [k, keyValueMap.get(k)]); | ||
| return _cache._entries; | ||
| } | ||
| function fromValue(value, options) { | ||
| if (options?.ignoreCase && typeof value === "string") { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap(); | ||
| const key = lcValueKeyMap.get(value.toLowerCase()); | ||
| if (!key) return void 0; | ||
| return keyValueMap.get(key); | ||
| } | ||
| if (!_cache._valueKeyMap.has(value)) return void 0; | ||
| return value; | ||
| } | ||
| function fromKey(key, options) { | ||
| const keyValueMap = _cache._keyValueMap ?? createKeyValueMap(); | ||
| if (options?.ignoreCase && typeof key === "string") { | ||
| const lcKeyValueMap = _cache._lcKeyValueMap ?? createLowerCaseKeyValueMap(); | ||
| return lcKeyValueMap.get(key.toLowerCase()); | ||
| } | ||
| return keyValueMap.get(`${key}`); | ||
| } | ||
| function keyFromValue(value, options) { | ||
| if (options?.ignoreCase && typeof value === "string") { | ||
| const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap(); | ||
| return lcValueKeyMap.get(value.toLowerCase()); | ||
| } | ||
| return _cache._valueKeyMap.get(value); | ||
| } | ||
| function hasKey(key, options) { | ||
| return fromKey(key, options) != null; | ||
| } | ||
| function hasValue(value, options) { | ||
| return fromValue(value, options) != null; | ||
| } | ||
| function keys() { | ||
| return _cache._keys; | ||
| } | ||
| function values() { | ||
| return _cache._values ?? createValues(); | ||
| } | ||
| function entries() { | ||
| return _cache._entries ?? createEntries(); | ||
| } | ||
| function* valueIterator() { | ||
| for (const v of values()) { | ||
| yield v; | ||
| } | ||
| } | ||
| function setAllLabels(allLabels) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| for (const [v, labels] of Object.entries(allLabels)) { | ||
| const value = fromValue(v); | ||
| if (value != null) { | ||
| valueLabelMap.set(value, labels); | ||
| } | ||
| } | ||
| } | ||
| function setLabels(value, labels) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| valueLabelMap.set(value, labels); | ||
| } | ||
| function getLabels(value) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| return valueLabelMap.get(value) ?? {}; | ||
| } | ||
| function getLabel(value, locale) { | ||
| const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap(); | ||
| const labels = valueLabelMap.get(value) ?? {}; | ||
| if (!locale) { | ||
| for (const label of Object.values(labels)) { | ||
| return label ?? `${value}`; | ||
| } | ||
| } | ||
| return labels[locale] ?? `${value}`; | ||
| } | ||
| return { | ||
| fromValue, | ||
| fromKey, | ||
| keyFromValue, | ||
| hasKey, | ||
| hasValue, | ||
| keys: () => keys(), | ||
| values: () => values(), | ||
| entries: () => entries(), | ||
| [Symbol.iterator]: valueIterator, | ||
| setAllLabels, | ||
| setLabels, | ||
| getLabels, | ||
| getLabel | ||
| }; | ||
| } | ||
| Enum.fromArray = (enumeration) => { | ||
| let arr = enumeration; | ||
| if (!Array.isArray(arr)) arr = []; | ||
| const enm = arr.reduce((acc, v) => { | ||
| acc[v] = v; | ||
| return acc; | ||
| }, {}); | ||
| return enm; | ||
| }; | ||
| export { | ||
| Enum | ||
| }; | ||
| //# sourceMappingURL=index.js.map |
| {"version":3,"sources":["../src/superenum.ts"],"sourcesContent":["/**\n * Create an enum type from an enum like object or array.\n */\nexport type EnumType<T> = T[keyof T];\n\n/**\n * Options for the {@link Superenum.fromValue} function\n */\nexport interface FromValueOptions {\n /**\n * Ignore case when validating the enum value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.fromKey} function\n */\nexport interface FromKeyOptions {\n /**\n * Ignore case when getting the enum value from the key\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.keyFromValue} function\n */\nexport interface KeyFromValueOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.hasKey} function\n */\nexport interface HasKeyOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * Options for the {@link Superenum.hasValue} function\n */\nexport interface HasValueOptions {\n /**\n * Ignore case when getting the enum key from the value\n */\n ignoreCase?: boolean;\n}\n\n/**\n * i18n labels for enum values.\n */\nexport interface Labels {\n [key: string]: string;\n}\n\n/**\n * Array Enum declaration\n */\nexport type ArrayEnum<KV extends EnumKey> = ReadonlyArray<KV>;\n\n/**\n * Convert an ArrayEnum type to an ObjectEnum\n */\nexport type ArrayEnumToObjectEnum<T extends ReadonlyArray<string>> = {\n [K in T[number]]: K;\n};\n\nexport interface Superenum<\n K extends EnumKey = EnumKey,\n V extends EnumValue = EnumValue,\n T extends ObjectEnum<K, V> = ObjectEnum<K, V>,\n> {\n /**\n * Validate a possible enum value, returning the enum value if valid, otherwise undefined.\n *\n * Since an enum value is just the value, then all this function does is check to see if the value exists on the enum, and if\n * so returns it cast to the enum type, otherwise it returns undefined.\n *\n * Note: If the enum has duplicate values when lower-cased and\n * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to validate\n * @param options - options for the function\n * @returns the enum value, or undefined if the value cannot be matched to the enum\n */\n fromValue(value: unknown | null | undefined, options?: FromValueOptions): EnumType<T> | undefined;\n\n /**\n * Get an enum value from its key, returning the value if key valid, otherwise undefined.\n *\n * Note: If the enum has duplicate keys when lower-cased and\n * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.\n *\n * @param key - the enum key to convert to enum value\n * @param options - options for the function\n * @returns the enum represented by the key, or undefined if the key cannot be matched to the enum\n */\n fromKey(\n key: EnumKey | number | null | undefined,\n options?: FromKeyOptions,\n ): EnumType<T> | undefined;\n\n /**\n * Get an enum key from its value, returning the key if value valid, otherwise undefined.\n *\n * Note: If the enum has duplicate values when lower-cased and\n * {@link FromValueOptions.ignoreCase} is true, the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to convert to enum key\n * @param options - options for the function\n * @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum\n */\n keyFromValue(\n value: unknown | null | undefined,\n options?: KeyFromValueOptions,\n ): string | undefined;\n\n /**\n * Check if an enum has a value, returning true if yes, otherwise false.\n *\n * Note: If the enum has duplicate values (or duplicate values when lower-cased if\n * {@link HasValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate.\n *\n * @param value - the enum value to check\n * @param options - options for the function\n * @returns true if the enum has the value, otherwise false\n */\n hasValue(value: EnumType<T> | null | undefined, options?: HasValueOptions): boolean;\n\n /**\n * Check if an enum has a key, returning true if yes, otherwise false.\n *\n * Note: If the enum has duplicate keys when lower-cased and\n * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate.\n *\n * @param key - the enum key to check\n * @param options - options for the function\n * @returns true if the enum has the key, otherwise false\n */\n hasKey(key: EnumKey | null | undefined, options?: HasKeyOptions): boolean;\n\n /**\n * Get an array of the enum values.\n *\n * @returns iterator over the enum values\n */\n values(): readonly EnumType<T>[];\n\n /**\n * Get an array of the enum keys.\n *\n * @returns iterator over the enum values\n */\n keys(): readonly ExtractEnumKey<K, V, T>[];\n\n /**\n * Get an array of the enum entries.\n *\n * @returns iterator over the enum values\n */\n entries(): readonly [ExtractEnumKey<K, V, T>, EnumType<T>][];\n\n /**\n * An iterator that iterates the enum values.\n *\n * @returns iterator over the enum values\n */\n [Symbol.iterator](): IterableIterator<EnumType<T>>;\n\n /**\n * Set i18n labels for all enum values.\n *\n * @param allLabels - an object containing i18n labels for each enum value\n */\n setAllLabels(allLabels: { [key: EnumValue]: Labels }): void;\n\n /**\n * Set i18n labels for a specific enum value.\n *\n * @param value - the enum value to set i18n labels for\n * @param labels - an object containing i18n labels for the enum value\n */\n setLabels(value: EnumType<T>, labels: Labels): void;\n\n /**\n * Get i18n labels for a specific enum value.\n *\n * @param value - the enum value to get i18n labels for\n * @returns an object containing i18n labels for the enum value\n */\n getLabels(value: EnumType<T>): Labels;\n\n /**\n * Get a label for a specific enum value in a specific locale.\n *\n * If no locale is provided, it will return the first label that was set.\n * If no label is found for the value, it will return the value as a string.\n *\n * @param value - the enum value to get the label for\n * @param locale - the locale to get the label for\n * @returns the label for the enum value in the specified locale\n */\n getLabel(value: EnumType<T>, locale?: string): string;\n}\n\ntype EnumKey = string;\ntype EnumValue = string | number;\ntype ExtractEnumKey<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>> = keyof T;\n\ntype GenericEnum = Readonly<Record<EnumKey, EnumValue>>;\n\ntype ObjectEnum<K extends EnumKey, V extends EnumValue> = { [key in K]: V };\n\ninterface Cache {\n _keys: EnumKey[];\n _valueKeyMap: Map<EnumValue, EnumKey>;\n _keyValueMap?: Map<EnumKey, EnumValue>;\n _lcValueKeyMap?: Map<EnumValue, EnumKey>;\n _lcKeyValueMap?: Map<EnumKey, EnumValue>;\n _valueLabelMap?: Map<EnumValue, Labels>;\n _values?: EnumValue[];\n _entries?: [EnumKey, EnumValue][];\n}\n\nconst CACHED_ENUMS = new WeakMap<GenericEnum, Cache>();\n\n/**\n * Wraps an enum or enum-like object to provide methods for interacting with it.\n *\n * Uses a WeakMap and lazy instantiation to cache the enum's keys, values, and labels\n * for fast performance while keeping memory footprint small.\n *\n * @param enm - an enum or enum like object\n * @returns a Superenum object that provides methods to interact with the enum\n */\nfunction Enum<K extends string, V extends string | number, T extends ObjectEnum<K, V>>(\n enm: T,\n): Superenum<K, V, T> {\n let _cache: Cache = CACHED_ENUMS.get(enm) as Cache;\n\n // Get the enum as a generic object\n const enmAny = enm as unknown as Record<string, EnumValue>;\n\n if (!_cache) {\n // Get iteration keys from the enum object (ignore reverse mapped integers)\n const enmKeys: EnumKey[] = [];\n for (const key in enm) {\n const nkey = Number(key);\n const isReverseKey = !isNaN(nkey) && enmAny[enmAny[nkey]] === nkey;\n\n if (!isReverseKey) {\n enmKeys.push(key);\n }\n }\n\n const newCache: Cache = {\n _keys: enmKeys,\n _valueKeyMap: new Map(),\n } as Cache;\n\n // Fill keyValueMap and lcKeyValueMap, valueKeyMap and lcValueKeyMap\n for (const key of newCache._keys) {\n const value = enmAny[key];\n newCache._valueKeyMap.set(value, key);\n }\n\n CACHED_ENUMS.set(enm, newCache);\n _cache = newCache;\n }\n\n function createKeyValueMap(): Map<EnumKey, EnumValue> {\n const newMap = new Map<EnumKey, EnumValue>();\n for (const key of _cache._keys) {\n const value = enmAny[key] as EnumValue;\n newMap.set(key, value);\n }\n _cache._keyValueMap = newMap;\n return newMap;\n }\n\n function createLowerCaseValueKeyMap(): Map<EnumValue, EnumKey> {\n const newMap = new Map<EnumValue, EnumKey>();\n for (const key of _cache._keys) {\n const value = enmAny[key];\n const lcValue = typeof value === 'string' ? value.toLowerCase() : value;\n newMap.set(lcValue, key);\n }\n _cache._lcValueKeyMap = newMap;\n\n return newMap;\n }\n\n function createLowerCaseKeyValueMap(): Map<EnumKey, EnumValue> {\n const newMap = new Map<EnumKey, EnumValue>();\n for (const key of _cache._keys) {\n const value = enmAny[key];\n newMap.set(key.toLowerCase(), value as EnumValue);\n }\n _cache._lcKeyValueMap = newMap;\n return newMap;\n }\n\n function createValueLabelMap(): Map<EnumValue, Labels> {\n const newMap = new Map<EnumValue, Labels>();\n _cache._valueLabelMap = newMap;\n return newMap;\n }\n\n function createValues() {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n _cache._values = _cache._keys.map((k) => keyValueMap.get(k)!);\n return _cache._values;\n }\n\n function createEntries() {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n _cache._entries = _cache._keys.map((k) => [k, keyValueMap.get(k)!]);\n return _cache._entries;\n }\n\n function fromValue(value: EnumValue, options?: FromValueOptions) {\n if (options?.ignoreCase && typeof value === 'string') {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap();\n const key = lcValueKeyMap.get(value.toLowerCase());\n if (!key) return undefined;\n return keyValueMap.get(key);\n }\n if (!_cache._valueKeyMap.has(value)) return undefined;\n return value;\n }\n\n function fromKey(key: EnumKey, options?: FromKeyOptions) {\n const keyValueMap = _cache._keyValueMap ?? createKeyValueMap();\n if (options?.ignoreCase && typeof key === 'string') {\n const lcKeyValueMap = _cache._lcKeyValueMap ?? createLowerCaseKeyValueMap();\n return lcKeyValueMap.get(key.toLowerCase());\n }\n return keyValueMap.get(`${key}`);\n }\n\n function keyFromValue(value: EnumValue, options?: KeyFromValueOptions) {\n if (options?.ignoreCase && typeof value === 'string') {\n const lcValueKeyMap = _cache._lcValueKeyMap ?? createLowerCaseValueKeyMap();\n return lcValueKeyMap.get(value.toLowerCase());\n }\n return _cache._valueKeyMap.get(value);\n }\n\n function hasKey(key: EnumKey, options?: HasKeyOptions) {\n return fromKey(key, options) != null;\n }\n\n function hasValue(value: EnumValue, options?: HasValueOptions) {\n return fromValue(value, options) != null;\n }\n\n function keys() {\n return _cache._keys;\n }\n\n function values() {\n return _cache._values ?? createValues();\n }\n\n function entries() {\n return _cache._entries ?? createEntries();\n }\n\n function* valueIterator() {\n for (const v of values()) {\n yield v;\n }\n }\n\n function setAllLabels(allLabels: { [key: EnumValue]: Labels }): void {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n for (const [v, labels] of Object.entries(allLabels)) {\n const value = fromValue(v);\n if (value != null) {\n valueLabelMap.set(value, labels);\n }\n }\n }\n\n function setLabels(value: EnumValue, labels: Labels): void {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n valueLabelMap.set(value, labels);\n }\n\n function getLabels(value: EnumValue): Labels {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n return valueLabelMap.get(value) ?? {};\n }\n\n function getLabel(value: EnumValue, locale?: string): string {\n const valueLabelMap = _cache._valueLabelMap ?? createValueLabelMap();\n const labels = valueLabelMap.get(value) ?? {};\n if (!locale) {\n for (const label of Object.values(labels)) {\n return label ?? `${value}`;\n }\n }\n return labels[locale as string] ?? `${value}`;\n }\n\n return {\n fromValue,\n fromKey,\n keyFromValue,\n hasKey,\n hasValue,\n keys: () => keys(),\n values: () => values(),\n entries: () => entries(),\n [Symbol.iterator]: valueIterator,\n setAllLabels,\n setLabels,\n getLabels,\n getLabel,\n } as unknown as Superenum<K, V, T>;\n}\n\nEnum.fromArray = <KV extends Readonly<EnumKey>, T extends ArrayEnum<KV>>(\n enumeration: T,\n): ArrayEnumToObjectEnum<T> => {\n let arr: ArrayEnum<KV> = enumeration;\n if (!Array.isArray(arr)) arr = [];\n\n const enm = arr.reduce((acc, v) => {\n acc[v] = v;\n return acc;\n }, {});\n\n return enm as ArrayEnumToObjectEnum<T>;\n};\n\nexport type EnumFunc = typeof Enum;\n\nexport { Enum };\n"],"mappings":";AAuOA,IAAM,eAAe,oBAAI,QAA4B;AAWrD,SAAS,KACP,KACoB;AACpB,MAAI,SAAgB,aAAa,IAAI,GAAG;AAGxC,QAAM,SAAS;AAEf,MAAI,CAAC,QAAQ;AAEX,UAAM,UAAqB,CAAC;AAC5B,eAAW,OAAO,KAAK;AACrB,YAAM,OAAO,OAAO,GAAG;AACvB,YAAM,eAAe,CAAC,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,QAAQ;AAAA,IACvB,CAAC,OAAO,QAAQ,GAAG;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA,KAAK,YAAY,CACf,gBAC6B;AAC7B,MAAI,MAAqB;AACzB,MAAI,CAAC,MAAM,QAAQ,GAAG,EAAG,OAAM,CAAC;AAEhC,QAAM,MAAM,IAAI,OAAO,CAAC,KAAK,MAAM;AACjC,QAAI,CAAC,IAAI;AACT,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;","names":[]} |
+78
-41
| { | ||
| "name": "@ncoderz/superenum", | ||
| "version": "0.2.5", | ||
| "version": "1.0.0", | ||
| "description": "Simple, typesafe enums in TypeScript, fully compatible with standard JavaScript", | ||
| "author": "zx-ncoderz", | ||
| "author": "six5536", | ||
| "license": "BSD-2-Clause", | ||
| "main": "dist/cjs/superenum.js", | ||
| "module": "dist/esm/superenum.js", | ||
| "types": "dist/types/superenum.d.ts", | ||
| "type": "module", | ||
| "main": "./dist/index.cjs", | ||
| "module": "./dist/index.js", | ||
| "types": "./dist/index.d.ts", | ||
| "browser": "./dist/browser/superenum.global.js", | ||
| "jsdelivr": "./dist/browser/superenum.global.js", | ||
| "unpkg": "./dist/browser/superenum.global.js", | ||
| "exports": { | ||
| "./browser": { | ||
| "browser": "./dist/browser/superenum.global.js", | ||
| "import": "./dist/browser/superenum.global.js", | ||
| "require": "./dist/browser/superenum.global.js" | ||
| }, | ||
| "./esm": { | ||
| "import": "./dist/index.js", | ||
| "require": "./dist/index.js" | ||
| }, | ||
| "./cjs": { | ||
| "import": "./dist/index.cjs", | ||
| "require": "./dist/index.cjs" | ||
| }, | ||
| ".": { | ||
| "import": "./dist/index.js", | ||
| "require": "./dist/index.cjs", | ||
| "default": "./dist/index.js" | ||
| } | ||
| }, | ||
| "files": [ | ||
| "dist" | ||
| "dist", | ||
| "README.md", | ||
| "LICENSE" | ||
| ], | ||
| "scripts": { | ||
| "build": "run lint && tsc && tsc --module ES6 --outDir 'dist/esm' && rollup -c && run build-doc", | ||
| "build-cjs": "tsc", | ||
| "build-esm": "tsc --module ES6 --outDir 'dist/esm'", | ||
| "build-iife": "tsc && rollup -c", | ||
| "build-doc": "typedoc", | ||
| "test": "jest --coverage", | ||
| "publish": "yarn npm publish", | ||
| "prepublish": "run lint && run clean && run build && run test", | ||
| "clean": "shx rm -rf ./dist", | ||
| "dev": "node ./bin/dev.ts", | ||
| "build": "npm run lint && npm run typecheck && tsup", | ||
| "build:watch": "tsup --watch", | ||
| "test": "vitest", | ||
| "test-ci": "vitest run", | ||
| "test-src": "vitest ./test/superenum.src.test.ts", | ||
| "typecheck": "tsc --noEmit", | ||
| "lint": "eslint --max-warnings 0 -- './**/*.@(tsx|ts|jsx|js|mjs|cjs)'", | ||
| "ncu": "yarn dlx npm-check-updates -i" | ||
| "lint-fix": "eslint --fix --max-warnings 0 -- './**/*.@(tsx|ts|jsx|js|mjs|cjs)'", | ||
| "format": "prettier --write 'src/**/*.{ts,tsx}' '*.{json,md}'", | ||
| "format-check": "prettier --check 'src/**/*.{ts,tsx}' '*.{json,md}'", | ||
| "docs": "typedoc", | ||
| "prepublishOnly": "npm run clean && npm run build && npm run test-ci && npm run docs", | ||
| "clean": "node scripts/clean.ts" | ||
| }, | ||
| "packageManager": "yarn@4.5.0", | ||
| "devEngines": { | ||
| "runtime": { | ||
| "name": "node", | ||
| "version": "^24.0.0", | ||
| "onFail": "error" | ||
| }, | ||
| "packageManager": { | ||
| "name": "npm", | ||
| "version": "^11.0.0", | ||
| "onFail": "error" | ||
| } | ||
| }, | ||
| "engines": { | ||
| "node": ">=10", | ||
| "npm": ">=6.8.0" | ||
| "node": ">=16", | ||
| "npm": ">=8" | ||
| }, | ||
@@ -41,2 +81,4 @@ "keywords": [ | ||
| "intellisense", | ||
| "code completion", | ||
| "autocomplete", | ||
| "ts", | ||
@@ -49,29 +91,24 @@ "js" | ||
| }, | ||
| "contributors": [ | ||
| "Richard Sewell (https://github.com/six5536)" | ||
| ], | ||
| "devDependencies": { | ||
| "@types/eslint-plugin-prettier": "^3.1.3", | ||
| "@types/jest": "^29.5.13", | ||
| "@types/node": "^22.7.4", | ||
| "@typescript-eslint/eslint-plugin": "^8.7.0", | ||
| "@typescript-eslint/parser": "^8.7.0", | ||
| "core-js": "^3.38.1", | ||
| "@types/fs-extra": "^11.0.4", | ||
| "@types/node": "^24.1.0", | ||
| "eslint": "^9.11.1", | ||
| "eslint-config-prettier": "^9.1.0", | ||
| "eslint-plugin-arca": "^0.16.0", | ||
| "eslint-config-prettier": "^10.1.8", | ||
| "eslint-plugin-json": "^4.0.1", | ||
| "eslint-plugin-prettier": "^5.2.1", | ||
| "jest": "^29.7.0", | ||
| "jest-environment-node": "^29.7.0", | ||
| "jest-junit": "^16.0.0", | ||
| "eslint-plugin-simple-import-sort": "^12.1.1", | ||
| "fs-extra": "^11.3.0", | ||
| "prettier": "^3.3.3", | ||
| "rollup": "^4.22.5", | ||
| "rollup-plugin-babel-minify": "^10.0.0", | ||
| "rollup-plugin-commonjs": "^10.1.0", | ||
| "rollup-plugin-node-resolve": "^5.2.0", | ||
| "rollup-plugin-terser": "^7.0.2", | ||
| "shx": "^0.3.4", | ||
| "ts-jest": "^29.2.5", | ||
| "typedoc": "^0.26.7", | ||
| "terser": "^5.43.1", | ||
| "tsup": "^8.5.0", | ||
| "typedoc": "^0.28.0", | ||
| "typedoc-plugin-markdown": "^4.2.8", | ||
| "typescript": "^5.6.2" | ||
| } | ||
| } | ||
| "typescript": "^5.6.2", | ||
| "typescript-eslint": "^8.35.0", | ||
| "vitest": "^3.2.4" | ||
| }, | ||
| "dependencies": {} | ||
| } |
+261
-208
@@ -1,30 +0,34 @@ | ||
| @ncoderz/superenum | ||
| ================ | ||
| # Superenum | ||
|  | ||
|  | ||
|  | ||
|  | ||
| Simple, typesafe enums in TypeScript, fully compatible with standard JavaScript. | ||
| `🚀 The enum utility that TypeScript forgot` — _JavaScript too!_ | ||
| ## Why? | ||
| ## Why @ncoderz/superenum? | ||
| Ever wanted Validation, Iteration, Key-Lookups, Localization for your enums in Typescript or JavaScript? | ||
| The standard TypeScript enum implementation is over-complicated, missing basic features, and is not easily compatible with standard JavaScript enums. | ||
| Ever wanted it to be so simple you'll use it everywhere? | ||
| @ncoderz/superenum provides an alternative that is: | ||
| - an extension of standard JavaScript object enums | ||
| - simple to use | ||
| - type-safe | ||
| - supports IDE autocompletion | ||
| - iteration order can be guaranteed | ||
| - is interoperable with standard JavaScript enums | ||
| - works in node or the browser | ||
| - has a very small code footprint (< 1kB minified + gzipped) | ||
| superenum is the enum utility that TS forgot: | ||
| Additionally, the library is committed to: | ||
| - an API that will always remain backwards compatible | ||
| - no dependencies | ||
| - permissive license ([BSD-2-Clause](https://opensource.org/licenses/BSD-2-Clause)) | ||
| - fixing bugs | ||
| - 🚀 Super-powers for your enums | ||
| - ✅ Input validation | ||
| - 📚 Iterable, order guaranteed | ||
| - ↔️ key ⬌ value conversion | ||
| - 🌐 Localization (i18n) | ||
| - ✨ Simple to use | ||
| - 🔒 Type-safe | ||
| Additionally: | ||
| - 👍 Works with Node 24 without `--experimental-transform-types` | ||
| - 🌐 Works with TypeScript or JavaScript enums | ||
| - 🖥️ Works in NodeJS, Deno, Bun, or the browser | ||
| - 📦 Very small code footprint (~1.5kB minified + gzipped) | ||
| - 🛠️ No dependencies | ||
| - 📜 Permissive license ([BSD-2-Clause](https://opensource.org/licenses/BSD-2-Clause)) | ||
@@ -34,125 +38,185 @@ ## Installation | ||
| ```sh | ||
| npm install @ncoderz/superenum | ||
| pnpm install @ncoderz/superenum | ||
| yarn add @ncoderz/superenum | ||
| npm install --save @ncoderz/superenum | ||
| deno add @ncoderz/superenum | ||
| bun add @ncoderz/superenum | ||
| ``` | ||
| Using jsDelivr CDN (ES6 IFFE module): | ||
| ```html | ||
| <script src="https://cdn.jsdelivr.net/npm/@ncoderz/superenum@latest/dist/browser/superenum.global.js"></script> | ||
| ``` | ||
| Using unpkg CDN (ES6 IFFE module): | ||
| ```html | ||
| <script src="https://unpkg.com/@ncoderz/superenum@latest/dist/browser/superenum.global.js"></script> | ||
| ``` | ||
| Replace `latest` with a specific version in either of the URLs above to use a specific version. | ||
| ## Importing | ||
| `@ncoderz/superenum` can be used via ES Module import, CommonJS, or as a script import directly in the browser. | ||
| ```ts | ||
| import { superenum, EnumType } from '@ncoderz/superenum'; | ||
| import { Enum } from '@ncoderz/superenum'; | ||
| ``` | ||
| ```ts | ||
| const { superenum, EnumType } = require('@ncoderz/superenum'); | ||
| const { Enum } = require('@ncoderz/superenum'); | ||
| ``` | ||
| ```html | ||
| <script src="https://cdn.jsdelivr.net/npm/@ncoderz/superenum/dist/browser/superenum.min.js"></script> | ||
| <script | ||
| const { superenum } = window.superenum; | ||
| <script src="https://cdn.jsdelivr.net/npm/@ncoderz/superenum@latest/dist/browser/superenum.global.js"></script> | ||
| <script> | ||
| const { Enum } = window.superenum; | ||
| </script> | ||
| ``` | ||
| ## Enum Declaration | ||
| Enums are declared as JavaScript objects wrapped with the `superenum.fromObject(enumObject)` function. | ||
| ## Basic Usage | ||
| As long as the keys and values of the object are constants, or TypeScript can infer a constant value, then | ||
| the enum will be typesafe and IDE auto-completion will work. | ||
| ```ts | ||
| import { Enum, EnumType } from '@ncoderz/superenum'; | ||
| Enums can also be declared as JavaScript arrays using `superenum.fromArray(enumArray)`. These will be expanded to objects with the same keys as values, and they will behave as if they had be declared as such. | ||
| // Standard TypeScript enum | ||
| enum MyEnum { | ||
| node = 'node', | ||
| chrome = 'chrome', | ||
| safari = 'safari', | ||
| }; | ||
| ```ts | ||
| // String enum | ||
| const MyEnum = superenum({ // ALIAS: superenum.fromObject({ | ||
| // ALTERNATIVE: Standard object style enum | ||
| const MyEnum { | ||
| node: 'node', | ||
| chrome: 'chrome', | ||
| safari: 'safari', | ||
| }); | ||
| type MyEnumType = EnumType<typeof MyEnum>; // Optional type declaration | ||
| }; | ||
| // Equivalent declaration using an array | ||
| const MyEnumFromArray = superenum.fromArray([ | ||
| // ALTERNATIVE: String enums can also be declared | ||
| // short-hand using arrays (keys and values are the same, so lower case in this case) | ||
| const MyEnum = Enum.fromArray([ | ||
| 'node', | ||
| 'chrome', | ||
| 'safari', | ||
| 'safari' | ||
| ]); | ||
| type MyEnumFromArrayType = EnumType<typeof MyEnumFromArray> // Optional type declaration | ||
| // Numeric enum | ||
| const MyNumericEnum = superenum({ | ||
| node: 0, | ||
| chrome: 1, | ||
| safari: 2, | ||
| }); | ||
| type MyNumericEnumType = EnumType<typeof MyNumericEnum> // Optional type declaration | ||
| // Type for object and array enum declarations | ||
| // (not necessary for TypeScript enums as enum is already also type) | ||
| type MyEnum = EnumType<typeof MyEnum>; | ||
| ``` | ||
| // Mixed enum with different values as string keys | ||
| const MyMixedEnum = superenum({ | ||
| node: 'NodeJS', | ||
| chrome: 1, | ||
| safari: 'MacOSSafari', | ||
| }); | ||
| type MyMixedEnumType = EnumType<typeof MyMixedEnum> // Optional type declaration | ||
| #### Validation | ||
| ```ts | ||
| enum MyEnum { | ||
| NODE = 'node', | ||
| CHROME = 'chrome', | ||
| SAFARI = 'safari', | ||
| } | ||
| // Validation | ||
| const value = Enum(MyEnum).fromValue('node'); // MyEnum.NODE | ||
| // Validation with default | ||
| const value = Enum(MyEnum).fromValue('not supported') ?? MyEnum.SAFARI; // MyEnum.SAFARI | ||
| ``` | ||
| ## Basic Usage | ||
| #### Iteration | ||
| ```ts | ||
| const MyEnum = superenum({ | ||
| node: 'node', | ||
| chrome: 'chrome', | ||
| safari: 'MacOSSafari', | ||
| }); | ||
| type MyEnumType = EnumType<typeof MyEnum>; | ||
| enum MyEnum { | ||
| NODE = 'node', | ||
| CHROME = 'chrome', | ||
| SAFARI = 'safari', | ||
| } | ||
| // End enum declaration | ||
| // Iteration (values) | ||
| for (const value of Enum(MyEnum) /* or Enum(MyEnum).values() */) { | ||
| console.log(value); // 'node', 'chrome', 'safari' | ||
| } | ||
| // Basic variable and comparison | ||
| const value: MyEnumType = MyEnum.node; | ||
| // Iteration (keys) | ||
| for (const key of Enum(MyEnum).keys()) { | ||
| console.log(key); // 'NODE', 'CHROME', 'SAFARI' | ||
| } | ||
| console.assert(value === MyEnum.node) // true | ||
| console.assert(value === 'node') // true | ||
| console.assert(value === MyEnum.chrome) // false | ||
| console.assert(value === 'firefox') // false | ||
| // Iteration (entries) | ||
| for (const entry of Enum(MyEnum).entries()) { | ||
| console.log(entry); // ['NODE', 'node'], ['CHROME', 'chrome'], ['SAFARI', 'safari'] | ||
| } | ||
| ``` | ||
| // Switch statements | ||
| switch (value) { | ||
| case MyEnum.node: // true | ||
| break; | ||
| case MyEnum.chrome: // false | ||
| break; | ||
| case MyEnum.safari: // false | ||
| break; | ||
| default: | ||
| #### key => value conversion | ||
| ```ts | ||
| enum MyEnum { | ||
| NODE = 'node', | ||
| CHROME = 'chrome', | ||
| SAFARI = 'safari', | ||
| } | ||
| switch (value) { | ||
| case 'node': // true | ||
| break; | ||
| case 'chrome': // false | ||
| break; | ||
| case 'MacOSSafari': // false | ||
| break; | ||
| case 'safari': // TS compiler error | ||
| break; | ||
| case 'something else': // TS compiler error | ||
| break; | ||
| default: | ||
| // Key to Value (fromKey) | ||
| const value = Enum(MyEnum).fromKey('NODE'); // MyEnum.node | ||
| ``` | ||
| #### value => key conversion | ||
| ```ts | ||
| enum MyEnum { | ||
| NODE = 'node', | ||
| CHROME = 'chrome', | ||
| SAFARI = 'safari', | ||
| } | ||
| // Value to Key (keyFromValue) | ||
| const key = Enum(MyEnum).keyFromValue(MyEnum.NODE); // 'NODE' | ||
| ``` | ||
| #### Localization (i18n) | ||
| ```ts | ||
| enum MyEnum { | ||
| HELLO = 'hello', | ||
| GOODBYE = 'goodbye', | ||
| } | ||
| // Localization (i18n) | ||
| // Set labels all at one | ||
| Enum(MyEnum).setAllLabels({ | ||
| [MyEnum.HELLO]: { | ||
| en: 'Hello', | ||
| de: 'Guten Tag', | ||
| }, | ||
| [MyEnum.GOODBYE]: { | ||
| en: 'Goodbye', | ||
| de: 'Auf Wiedersehen', | ||
| }, | ||
| }); | ||
| // Or set labels one by one | ||
| Enum(MyEnum).setLabels(MyEnum.HELLO, { en: 'Hello', de: 'Guten Tag' }); | ||
| Enum(MyEnum).setLabels(MyEnum.GOODBYE, { en: 'Goodbye', de: 'Auf Wiedersehen' }); | ||
| // Get a label in the first configured (default) language | ||
| Enum(MyEnum).getLabel(MyEnum.HELLO); // 'Hello' | ||
| // Get a label in a specific language | ||
| Enum(MyEnum).getLabel(MyEnum.HELLO, 'de'); // 'Guten Tag' | ||
| // If a locale does not exist, the enum value is returned | ||
| Enum(MyEnum).getLabel(MyEnum.HELLO, 'es'); // 'hello' | ||
| ``` | ||
| ## Validation | ||
| Validation is a common use case when reading data from an API, file or database. | ||
| `@ncoderz/superenum` makes this easy with `<enum>.fromValue()` which returns a typed enum or undefined if the | ||
| data does not match an enum value. | ||
| Validation is a common use case when reading data from an API, file, or database. | ||
| `@ncoderz/superenum` makes this easy with `Enum(<enum>).fromValue()` which returns a typed enum or undefined if the data does not match an enum value. | ||
| ```ts | ||
| const MyEnum = superenum.fromArray([ | ||
| 'node', | ||
| 'chrome', | ||
| 'safari', | ||
| ]); | ||
| const MyEnum = Enum.fromArray(['node', 'chrome', 'safari']); | ||
@@ -162,25 +226,25 @@ // End enum declaration | ||
| // Input values could come from external data / API | ||
| const valueNode = MyEnum.fromValue('node'); // MyEnum.node / 'node' | ||
| const valueChrome = MyEnum.fromValue('chrome'); // MyEnum.chrome / 'chrome' | ||
| const invalid = MyEnum.fromValue('surfari'); // undefined | ||
| const invalid2 = MyEnum.fromValue(undefined); // undefined | ||
| const valueNode = Enum(MyEnum).fromValue('node'); // MyEnum.node | ||
| const valueChrome = Enum(MyEnum).fromValue('chrome'); // MyEnum.chrome | ||
| const invalid = Enum(MyEnum).fromValue('surfari'); // undefined | ||
| const invalid2 = Enum(MyEnum).fromValue(undefined); // undefined | ||
| // Validate with default of MyEnum.node | ||
| const validOrDefault = MyEnum.fromValue('invalid') ?? MyEnum.node; // MyEnum.node / 'node' | ||
| const validOrDefault = Enum(MyEnum).fromValue('invalid') ?? MyEnum.node; // MyEnum.node | ||
| ``` | ||
| ## Iteration / forEach / map / reduce | ||
| It is easy to iterate the enum values, keys or entries. | ||
| The `<enum>` itself is iterable and will iterate the values in the defined key order. | ||
| It is easy to iterate the enum values, keys, or entries. | ||
| The `<enum>.values()`, `<enum>.keys()`, `<enum>.entries()` functions return arrays in the defined key order which | ||
| can be iterated, mapped, reduced, etc. | ||
| The `Enum(<enum>)` itself is iterable and will iterate the values in the defined key order. | ||
| The `Enum(<enum>).values()`, `Enum(<enum>).keys()`, `Enum(<enum>).entries()` functions return arrays in the defined key order which can be iterated, mapped, reduced, etc. | ||
| ```ts | ||
| const MyNumericEnum = superenum({ | ||
| node: 0, | ||
| chrome: 1, | ||
| safari: 2, | ||
| }); | ||
| enum MyNumericEnum = { | ||
| node = 0, | ||
| chrome = 1, | ||
| safari = 2, | ||
| }; | ||
@@ -190,4 +254,4 @@ // End enum declaration | ||
| // Iterate enum values | ||
| for (const value of MyNumericEnum) { | ||
| console.log(value) | ||
| for (const value of Enum(MyNumericEnum)) { | ||
| console.log(value); | ||
| } | ||
@@ -198,4 +262,4 @@ // 0 | ||
| for (const value of MyNumericEnum.values()) { | ||
| console.log(value) | ||
| for (const value of Enum(MyNumericEnum).values()) { | ||
| console.log(value); | ||
| } | ||
@@ -206,4 +270,4 @@ // 0 | ||
| MyNumericEnum.values().forEach((value) => { | ||
| console.log(value) | ||
| Enum(MyNumericEnum).values().forEach((value) => { | ||
| console.log(value); | ||
| }); | ||
@@ -214,4 +278,4 @@ // 0 | ||
| MyNumericEnum.values().map((value) => { | ||
| console.log(value + 1) | ||
| Enum(MyNumericEnum).values().map((value) => { | ||
| console.log(value + 1); | ||
| }); | ||
@@ -223,4 +287,4 @@ // 1 | ||
| // Iterate enum keys (forEach, map, etc also work on keys()) | ||
| for (const value of MyNumericEnum.keys()) { | ||
| console.log(value) | ||
| for (const value of Enum(MyNumericEnum).keys()) { | ||
| console.log(value); | ||
| } | ||
@@ -232,4 +296,4 @@ // node | ||
| // Iterate enum entries (forEach, map, etc also work on entries()) | ||
| for (const value of MyNumericEnum.entries()) { | ||
| console.log(value) | ||
| for (const value of Enum(MyNumericEnum).entries()) { | ||
| console.log(value); | ||
| } | ||
@@ -241,61 +305,47 @@ // [ 'node', 0 ] | ||
| The order of iteration is guaranteed unless an enum key can be converted to an integer. In this case it can be guaranteed by using `superenum.fromArray()` to initialise the enum, or by setting `EnumOptions.iterationKeys` to represent the desired iteration order. | ||
| #### A note on Iteration Order | ||
| ```ts | ||
| // Ensure iteration order when using integer keys mixed with strings and creating | ||
| // the object with `superenum() / superenum.fromObject() | ||
| // | ||
| // In this case if iterationKeys was not used, the iteration order would be defined | ||
| // by the JavaScript engine and would probably be: | ||
| // 1, 2, node, safari | ||
| Iteration order will be the order of declaration of items in the enum. | ||
| const MyMixedEnum = superenum({ | ||
| node: 0, | ||
| 1: 1, | ||
| safari: 2, | ||
| '2': 'two' | ||
| }, { | ||
| iterationKeys: ['node', 1, 'safari', '2'] | ||
| }); | ||
| However there is one exception which can affect object or array enums (NOT TypeScript enums). | ||
| // Iterate enum keys | ||
| for (const value of MyMixedEnum.keys()) { | ||
| console.log(value) | ||
| } | ||
| // node | ||
| // 1 | ||
| // safari | ||
| // 2 | ||
| If a key is a positive integer like string, for example '99', then it will be iterated before all | ||
| other keys. | ||
| ``` | ||
| This is a feature of how JavaScript engines store keys. It cannot be avoided without making | ||
| the library more complex, and it is only a very minor edge case. It is documented here for reference. | ||
| It does not affect TypeScript enums because they specifically forbid numeric like keys as otherwise | ||
| they would clash with the reverse lookups. | ||
| ## Enum value from enum key | ||
| There are use-cases where you might want to get an enum value from the enum key. | ||
| An example might be where the key is stored in a configuration file, and matched to a value in code. | ||
| This is possible with `<enum>.fromKey()` | ||
| This is possible with `Enum(<enum>).fromKey()` | ||
| ```ts | ||
| const MyEnum = superenum({ | ||
| const MyEnum = { | ||
| node: 0, | ||
| chrome: 1, | ||
| safari: 2, | ||
| }); | ||
| }; | ||
| type MyEnum = EnumType<typeof MyEnum>; | ||
| // End enum declaration | ||
| const nodeValue = MyEnum.fromKey('node'); // MyEnum.node / 0 | ||
| const invalidValue = MyEnum.fromKey('NoDe'); // undefined | ||
| const nodeValue2 = MyEnum.fromKey('NoDe', { | ||
| const nodeValue = Enum(MyEnum).fromKey('node'); // MyEnum.node | ||
| const invalidValue = Enum(MyEnum).fromKey('NoDe'); // undefined | ||
| const nodeValue2 = Enum(MyEnum).fromKey('NoDe', { | ||
| ignoreCase: true, | ||
| }); // MyEnum.node / 0 | ||
| }); // MyEnum.node | ||
| ``` | ||
| ## Enum key from enum value | ||
| There are use-cases where you might want to get an enum key from the enum value. An example might be for | ||
| logging purposes. | ||
| This is possible with `<enum>.keyFromValue()` | ||
| This is possible with `Enum(<enum>).keyFromValue()` | ||
@@ -311,74 +361,77 @@ ```ts | ||
| const nodeKey = MyEnum.keyFromValue('NodeJS'); // 'node' | ||
| const nodeKey2 = MyEnum.keyFromValue(MyEnum.node); // 'node' | ||
| const invalid = MyEnum.keyFromValue('node'); // undefined | ||
| const nodeKey = Enum(MyEnum).keyFromValue('NodeJS'); // 'node' | ||
| const nodeKey2 = Enum(MyEnum).keyFromValue(MyEnum.node); // 'node' | ||
| const invalid = Enum(MyEnum).keyFromValue('node'); // undefined | ||
| ``` | ||
| ## Metadata | ||
| Want to associate some data with a particular enum value? An example might be to store a set of description strings | ||
| against a set of keys... the possibilities are endless. | ||
| <!-- | ||
| This is possible with `<enum>.setMetadata()` and `<enum>.getMetadata()` | ||
| ## API | ||
| ```ts | ||
| const MyEnum = superenum.fromArray([ | ||
| 'node', | ||
| 'chrome', | ||
| 'safari', | ||
| ]); | ||
| [API Documentation](dist/docs/API.md) | ||
| --> | ||
| MyEnum.setMetadata(MyEnum.node, 'Node.js is an open-source, cross-platform...'); | ||
| MyEnum.setMetadata(MyEnum.chrome, 'Chrome is faster than fast – it’s engine...'); | ||
| MyEnum.setMetadata(MyEnum.safari, 'Safari is the best way to experience the...'); | ||
| ## Migration from version 0.x.x | ||
| // End enum declaration | ||
| Version 1 changed the philosophy to leave enum declarations as they are, and apply Superenum | ||
| features when required using a lightweight, weak map cache. | ||
| // Input value could come from external data / API | ||
| const valueNode = MyEnum.fromValue('node'); // MyEnum.node / 'node' | ||
| const desc = MyEnum.getMetadata(valueNode); // 'Node.js is an open-source, cross-platform...' | ||
| ### Declaration | ||
| ``` | ||
| ```ts | ||
| const MyEnum = superenum({ | ||
| key: 'value', | ||
| }); | ||
| ## API | ||
| // ==> | ||
| [API Documentation](docs/API.md) | ||
| const MyEnum = { | ||
| key: 'value', | ||
| }; | ||
| ``` | ||
| ## Feature Comparison | ||
| ### Function usage | ||
| | Feature | `@ncoderz/enum` (numeric and string) | TypeScript `enum` (numeric) | TypeScript `enum` (string) | | ||
| | ------- | ------------------------------------- | --------------------------- | -------------------------- | | ||
| | Compatible with simple JS enums | Yes | X | X | | ||
| | Mixed numeric and string keys | Yes | X | X | | ||
| | Compare value | `value === Enum.key` | `Enum[value] === Enum[Enum.key]` | `value === Enum.key` | ||
| | Validate external data to valid typed enum | `const val: EnumType = Enum.fromValue(value)` | `const val: Enum = ((Enum[value] === Enum[Enum.key]) ? value : undefined) as Enum` | `const val: Enum = ((value === Enum.key) ? value : undefined) as Enum` | ||
| | Value from key | `const val: EnumType = Enum.fromKey(key)` | `Enum[key]` - only if key is const; not very useful | `Object.entries(Enum).reduce((acc, [k,v]) => { if (acc) return acc; if (k === key) return v; }, '')` - not typed (is string) | | ||
| | Value from key safe? | Safe | No, will return key for invalid input which happens to be a valid value | Safe, but see above! | | ||
| | Key from value | `Enum.keyFromValue(value)` | `Enum[value]` | `Object.entries(Enum).reduce((acc, [k,v]) => { if (acc) return acc; if (v === value) return k; }, '')` | | ||
| | Key from value safe? | Safe | No, will return value for invalid input which happens to be a valid key | Safe, but see above! | | ||
| | Iterate values? | `Enum.values()` | `Object.values(Enum).filter((v) => isNaN(Number(v))` | `Object.values(Enum)` | ||
| | Iterate keys? | `Enum.keys()` | `Object.keys(Enum).filter((k) => !isNaN(Number(k))` | `Object.keys(Enum)` | | ||
| | Iterate entries? | `Enum.entries()` | `Object.entries(Enum).filter(([k,v]) => isNaN(Number(k)))` | `Object.entries(Enum)` | | ||
| | Associate metadata with an enum value | Yes | X | X | | ||
| | Declare just first number value and increment | X | Yes | N/A | | ||
| | Bloat code? | < 1kB | Built-in | Built-in | | ||
| | Fast? | Yes | Workarounds involve looping | Workarounds involve looping | | ||
| ```ts | ||
| const v = MyEnum.fromValue('value'); | ||
| // ==> | ||
| ## Limitations | ||
| import { Enum } from '@ncoderz/superenum'; | ||
| Enums may not use the keys: | ||
| const v = Enum(MyEnum).fromValue(); | ||
| ``` | ||
| `fromKey`, `fromValue`, `keyFromValue`, `setMetadata`, `getMetadata`, `keys`, `values`, `entries` | ||
| ## License | ||
| as these clash with the extension functions. | ||
| This open source software is licensed under the [BSD-2-Clause license](https://opensource.org/licenses/BSD-2-Clause). | ||
| If such a key is used, it will be overwitten with the extension function. | ||
| --- | ||
| ## License | ||
| ## Alternatives | ||
| This open source software is licenced under the [BSD-2-Clause licence](https://opensource.org/licenses/BSD-2-Clause). | ||
| - [ts-enum-util](https://github.com/UselessPickles/ts-enum-util) | ||
| ## Alternatives | ||
| ## Table of Contents | ||
| - [TypeScript enums](https://www.typescriptlang.org/docs/handbook/enums.html) | ||
| - [Superenum](#superenum) | ||
| - [Why?](#why) | ||
| - [Installation](#installation) | ||
| - [Importing](#importing) | ||
| - [Basic Usage](#basic-usage) | ||
| - [Validation](#validation) | ||
| - [Iteration](#iteration) | ||
| - [key =\> value conversion](#key--value-conversion) | ||
| - [value =\> key conversion](#value--key-conversion) | ||
| - [Localization (i18n)](#localization-i18n) | ||
| - [Validation](#validation-1) | ||
| - [Iteration / forEach / map / reduce](#iteration--foreach--map--reduce) | ||
| - [A note on Iteration Order](#a-note-on-iteration-order) | ||
| - [Enum value from enum key](#enum-value-from-enum-key) | ||
| - [Enum key from enum value](#enum-key-from-enum-value) | ||
| - [Migration from version 0.x.x](#migration-from-version-0xx) | ||
| - [Declaration](#declaration) | ||
| - [Function usage](#function-usage) | ||
| - [License](#license) | ||
| - [Alternatives](#alternatives) | ||
| - [Table of Contents](#table-of-contents) |
| !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).superenum={})}(this,(function(e){"use strict";var t,n=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){function n(e,t){var n;const o=Object.freeze,r=Object.defineProperty,u=Object.assign,s={enumerable:!1},a=new Map,i=new Map,l=new Map,f=new Map,c=new Map,p=(null!==(n=null==t?void 0:t.iterationKeys)&&void 0!==n?n:Object.keys(e)).map((e=>`${e}`));for(const[t,n]of Object.entries(e))a.set(t,n),l.set(t.toLowerCase(),n);for(const[e,t]of a){const n="string"==typeof t?t.toLowerCase():t;i.set(t,e),f.set(n,e)}const d=p.map((e=>a.get(e))),y=p.map((e=>[e,a.get(e)]));return(t=>{let n=e;function g(e,t){return(null==t?void 0:t.ignoreCase)&&"string"==typeof e?a.get(f.get(e.toLowerCase())):i.has(e)?e:void 0}Object.isExtensible(e)||(n=u({},e)),r(n,"fromKey",u({value:function(e,t){return(null==t?void 0:t.ignoreCase)&&"string"==typeof e?l.get(e.toLowerCase()):a.get(`${e}`)}},s)),r(n,"fromValue",u({value:g},s)),r(n,"keyFromValue",u({value:function(e,t){return(null==t?void 0:t.ignoreCase)&&"string"==typeof e?f.get(e.toLowerCase()):i.get(e)}},s)),r(n,"setMetadata",u({value:function(e,t,n){const o=g(e);null!=o&&c.set(o,t)}},s)),r(n,"getMetadata",u({value:function(e,t){return c.get(e)}},s)),r(n,Symbol.iterator,u({value:function(){let e=0;return{next:()=>e<p.length?{value:a.get(`${p[e++]}`),done:!1}:{done:!0}}}},s)),r(n,"values",u({value:()=>d},s)),r(n,"keys",u({value:()=>p},s)),r(n,"entries",u({value:()=>y},s));let v=n;return(null==t?void 0:t.noFreeze)||(v=o(n),o(p),o(d),o(y)),v})(t)}Object.defineProperty(t,"__esModule",{value:!0}),t.superenum=void 0;const o=n;t.superenum=o,o.fromObject=n,o.fromArray=function(e,t){Array.isArray(e)||(e=[]);const o=e.reduce(((e,t)=>(e[`${t}`]=t,e)),{});return(!t||t&&!t.iterationKeys)&&((t=Object.assign({},t)).iterationKeys=e),n(o,t)}})),o=(t=n)&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t,r=n.superenum;e.default=o,e.superenum=r,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
| //# sourceMappingURL=superenum.min.js.map |
| {"version":3,"file":"superenum.min.js","sources":["../cjs/superenum.js"],"sourcesContent":["\"use strict\";\n/*\n\nCopyright ©2022-24 Ncoderz Ltd\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the\nfollowing conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\ndisclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\nfollowing disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\nINCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\nUSE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.superenum = void 0;\nfunction fromArray(arr, options) {\n if (!Array.isArray(arr))\n arr = [];\n const enumeration = arr.reduce((acc, v) => {\n acc[`${v}`] = v;\n return acc;\n }, {});\n // Default the iteration keys to be the passed in arr if not set\n if (!options || (options && !options.iterationKeys)) {\n options = Object.assign({}, options);\n options.iterationKeys = arr;\n }\n return fromObject(enumeration, options);\n}\nfunction fromObject(enumeration, options) {\n var _a;\n // For reducing code size when minified\n const Object_freeze = Object.freeze;\n const Object_defineProperty = Object.defineProperty;\n const Object_assign = Object.assign;\n const definePropertyOptions = {\n enumerable: false,\n };\n const keyValueMap = new Map();\n const valueKeyMap = new Map();\n const lcKeyValueMap = new Map();\n const lcValueKeyMap = new Map();\n const metadataMap = new Map();\n const iterationKeys = ((_a = options === null || options === void 0 ? void 0 : options.iterationKeys) !== null && _a !== void 0 ? _a : Object.keys(enumeration)).map((k) => `${k}`);\n // Fill keyValueMap and lcKeyValueMap\n for (const [key, value] of Object.entries(enumeration)) {\n // key must be a string since it's an object property\n keyValueMap.set(key, value);\n lcKeyValueMap.set(key.toLowerCase(), value);\n }\n // Fill valueKeyMap and lcValueKeyMap\n for (const [key, value] of keyValueMap) {\n // value might be a number, so much check\n const lcValue = typeof value === 'string' ? value.toLowerCase() : value;\n valueKeyMap.set(value, key);\n lcValueKeyMap.set(lcValue, key);\n }\n const values = iterationKeys.map((k) => keyValueMap.get(k));\n const entries = iterationKeys.map((k) => [k, keyValueMap.get(k)]);\n const init = (options) => {\n let superEn = enumeration;\n // If original object is not extensible, so we have to make a copy\n if (!Object.isExtensible(enumeration)) {\n superEn = Object_assign({}, enumeration);\n }\n function fromValue(value, options) {\n if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof value === 'string') {\n return keyValueMap.get(lcValueKeyMap.get(value.toLowerCase()));\n }\n if (!valueKeyMap.has(value))\n return undefined;\n return value;\n }\n function fromKey(key, options) {\n if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof key === 'string') {\n return lcKeyValueMap.get(key.toLowerCase());\n }\n return keyValueMap.get(`${key}`);\n }\n function keyFromValue(value, options) {\n if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof value === 'string') {\n return lcValueKeyMap.get(value.toLowerCase());\n }\n return valueKeyMap.get(value);\n }\n function setMetadata(value, metadata, options) {\n options;\n const v = fromValue(value);\n if (v != null)\n metadataMap.set(v, metadata);\n }\n function getMetadata(value, options) {\n options;\n return metadataMap.get(value);\n }\n function valueIterator() {\n let i = 0;\n return {\n // [Symbol.iterator]() {\n // return this;\n // },\n next: () => {\n if (i < iterationKeys.length) {\n return { value: keyValueMap.get(`${iterationKeys[i++]}`), done: false };\n }\n return {\n done: true,\n };\n },\n };\n }\n // Add helper functions to the enum but so they cannot be enumerated\n Object_defineProperty(superEn, 'fromKey', Object_assign({\n value: fromKey,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'fromValue', Object_assign({\n value: fromValue,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'keyFromValue', Object_assign({\n value: keyFromValue,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'setMetadata', Object_assign({\n value: setMetadata,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'getMetadata', Object_assign({\n value: getMetadata,\n }, definePropertyOptions));\n Object_defineProperty(superEn, Symbol.iterator, Object_assign({\n value: valueIterator,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'values', Object_assign({\n value: () => values,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'keys', Object_assign({\n value: () => iterationKeys,\n }, definePropertyOptions));\n Object_defineProperty(superEn, 'entries', Object_assign({\n value: () => entries,\n }, definePropertyOptions));\n // Freeze the enum if required\n let res = superEn;\n if (!(options === null || options === void 0 ? void 0 : options.noFreeze)) {\n res = Object_freeze(superEn);\n Object_freeze(iterationKeys);\n Object_freeze(values);\n Object_freeze(entries);\n }\n return res;\n };\n return init(options);\n}\nconst superenum = fromObject;\nexports.superenum = superenum;\nsuperenum.fromObject = fromObject;\nsuperenum.fromArray = fromArray;\n//# sourceMappingURL=superenum.js.map"],"names":["fromObject","enumeration","options","_a","Object_freeze","Object","freeze","Object_defineProperty","defineProperty","Object_assign","assign","definePropertyOptions","enumerable","keyValueMap","Map","valueKeyMap","lcKeyValueMap","lcValueKeyMap","metadataMap","iterationKeys","keys","map","k","key","value","entries","set","toLowerCase","lcValue","values","get","superEn","fromValue","ignoreCase","has","isExtensible","metadata","v","Symbol","iterator","i","next","length","done","res","noFreeze","init","exports","superenum","fromArray","arr","Array","isArray","reduce","acc"],"mappings":"oUAuCA,SAASA,EAAWC,EAAaC,GAC7B,IAAIC,EAEJ,MAAMC,EAAgBC,OAAOC,OACvBC,EAAwBF,OAAOG,eAC/BC,EAAgBJ,OAAOK,OACvBC,EAAwB,CAC1BC,YAAY,GAEVC,EAAc,IAAIC,IAClBC,EAAc,IAAID,IAClBE,EAAgB,IAAIF,IACpBG,EAAgB,IAAIH,IACpBI,EAAc,IAAIJ,IAClBK,GAAoG,QAAlFhB,EAAKD,aAAyC,EAASA,EAAQiB,qBAAkC,IAAPhB,EAAgBA,EAAKE,OAAOe,KAAKnB,IAAcoB,KAAKC,GAAM,GAAGA,MAE/K,IAAK,MAAOC,EAAKC,KAAUnB,OAAOoB,QAAQxB,GAEtCY,EAAYa,IAAIH,EAAKC,GACrBR,EAAcU,IAAIH,EAAII,cAAeH,GAGzC,IAAK,MAAOD,EAAKC,KAAUX,EAAa,CAEpC,MAAMe,EAA2B,iBAAVJ,EAAqBA,EAAMG,cAAgBH,EAClET,EAAYW,IAAIF,EAAOD,GACvBN,EAAcS,IAAIE,EAASL,EAC9B,CACD,MAAMM,EAASV,EAAcE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X,EAAYiB,IAAI,GAAGX,EAAcqB,QAASG,MAAM,GAE7D,CACHA,MAAM,GAIrB,GAmBEhC,IACHJ,EAAsBwB,EAAS,SAAUtB,EAAc,CACnDe,MAAO,IAAMK,GACdlB,IACHJ,EAAsBwB,EAAS,OAAQtB,EAAc,CACjDe,MAAO,IAAML,GACdR,IACHJ,EAAsBwB,EAAS,UAAWtB,EAAc,CACpDe,MAAO,IAAMC,GACdd,IAEH,IAAIiC,EAAMb,EAOV,OANM7B,aAAyC,EAASA,EAAQ2C,YAC5DD,EAAMxC,EAAc2B,GACpB3B,EAAce,GACdf,EAAcyB,GACdzB,EAAcqB,IAEXmB,CAAG,EAEPE,CAAK5C,EAChB,CAzIAG,OAAOG,eAAeuC,EAAS,aAAc,CAAEvB,OAAO,IACtDuB,EAAiBC,eAAG,EAyIpB,MAAMA,EAAYhD,EAClB+C,EAAiBC,UAAGA,EACpBA,EAAUhD,WAAaA,EACvBgD,EAAUC,UA3IV,SAAmBC,EAAKhD,GACfiD,MAAMC,QAAQF,KACfA,EAAM,IACV,MAAMjD,EAAciD,EAAIG,QAAO,CAACC,EAAKjB,KACjCiB,EAAI,GAAGjB,KAAOA,EACPiB,IACR,CAAE,GAML,QAJKpD,GAAYA,IAAYA,EAAQiB,kBACjCjB,EAAUG,OAAOK,OAAO,CAAE,EAAER,IACpBiB,cAAgB+B,GAErBlD,EAAWC,EAAaC,EACnC"} |
| "use strict"; | ||
| /* | ||
| Copyright ©2022-24 Ncoderz Ltd | ||
| Redistribution and use in source and binary forms, with or without modification, are permitted provided that the | ||
| following conditions are met: | ||
| 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following | ||
| disclaimer. | ||
| 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the | ||
| following disclaimer in the documentation and/or other materials provided with the distribution. | ||
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, | ||
| INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
| SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, | ||
| WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE | ||
| USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| */ | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.superenum = void 0; | ||
| function fromArray(arr, options) { | ||
| if (!Array.isArray(arr)) | ||
| arr = []; | ||
| const enumeration = arr.reduce((acc, v) => { | ||
| acc[`${v}`] = v; | ||
| return acc; | ||
| }, {}); | ||
| // Default the iteration keys to be the passed in arr if not set | ||
| if (!options || (options && !options.iterationKeys)) { | ||
| options = Object.assign({}, options); | ||
| options.iterationKeys = arr; | ||
| } | ||
| return fromObject(enumeration, options); | ||
| } | ||
| function fromObject(enumeration, options) { | ||
| var _a; | ||
| // For reducing code size when minified | ||
| const Object_freeze = Object.freeze; | ||
| const Object_defineProperty = Object.defineProperty; | ||
| const Object_assign = Object.assign; | ||
| const definePropertyOptions = { | ||
| enumerable: false, | ||
| }; | ||
| const keyValueMap = new Map(); | ||
| const valueKeyMap = new Map(); | ||
| const lcKeyValueMap = new Map(); | ||
| const lcValueKeyMap = new Map(); | ||
| const metadataMap = new Map(); | ||
| const iterationKeys = ((_a = options === null || options === void 0 ? void 0 : options.iterationKeys) !== null && _a !== void 0 ? _a : Object.keys(enumeration)).map((k) => `${k}`); | ||
| // Fill keyValueMap and lcKeyValueMap | ||
| for (const [key, value] of Object.entries(enumeration)) { | ||
| // key must be a string since it's an object property | ||
| keyValueMap.set(key, value); | ||
| lcKeyValueMap.set(key.toLowerCase(), value); | ||
| } | ||
| // Fill valueKeyMap and lcValueKeyMap | ||
| for (const [key, value] of keyValueMap) { | ||
| // value might be a number, so much check | ||
| const lcValue = typeof value === 'string' ? value.toLowerCase() : value; | ||
| valueKeyMap.set(value, key); | ||
| lcValueKeyMap.set(lcValue, key); | ||
| } | ||
| const values = iterationKeys.map((k) => keyValueMap.get(k)); | ||
| const entries = iterationKeys.map((k) => [k, keyValueMap.get(k)]); | ||
| const init = (options) => { | ||
| let superEn = enumeration; | ||
| // If original object is not extensible, so we have to make a copy | ||
| if (!Object.isExtensible(enumeration)) { | ||
| superEn = Object_assign({}, enumeration); | ||
| } | ||
| function fromValue(value, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof value === 'string') { | ||
| return keyValueMap.get(lcValueKeyMap.get(value.toLowerCase())); | ||
| } | ||
| if (!valueKeyMap.has(value)) | ||
| return undefined; | ||
| return value; | ||
| } | ||
| function fromKey(key, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof key === 'string') { | ||
| return lcKeyValueMap.get(key.toLowerCase()); | ||
| } | ||
| return keyValueMap.get(`${key}`); | ||
| } | ||
| function keyFromValue(value, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof value === 'string') { | ||
| return lcValueKeyMap.get(value.toLowerCase()); | ||
| } | ||
| return valueKeyMap.get(value); | ||
| } | ||
| function setMetadata(value, metadata, options) { | ||
| options; | ||
| const v = fromValue(value); | ||
| if (v != null) | ||
| metadataMap.set(v, metadata); | ||
| } | ||
| function getMetadata(value, options) { | ||
| options; | ||
| return metadataMap.get(value); | ||
| } | ||
| function valueIterator() { | ||
| let i = 0; | ||
| return { | ||
| // [Symbol.iterator]() { | ||
| // return this; | ||
| // }, | ||
| next: () => { | ||
| if (i < iterationKeys.length) { | ||
| return { value: keyValueMap.get(`${iterationKeys[i++]}`), done: false }; | ||
| } | ||
| return { | ||
| done: true, | ||
| }; | ||
| }, | ||
| }; | ||
| } | ||
| // Add helper functions to the enum but so they cannot be enumerated | ||
| Object_defineProperty(superEn, 'fromKey', Object_assign({ | ||
| value: fromKey, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'fromValue', Object_assign({ | ||
| value: fromValue, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'keyFromValue', Object_assign({ | ||
| value: keyFromValue, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'setMetadata', Object_assign({ | ||
| value: setMetadata, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'getMetadata', Object_assign({ | ||
| value: getMetadata, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, Symbol.iterator, Object_assign({ | ||
| value: valueIterator, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'values', Object_assign({ | ||
| value: () => values, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'keys', Object_assign({ | ||
| value: () => iterationKeys, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'entries', Object_assign({ | ||
| value: () => entries, | ||
| }, definePropertyOptions)); | ||
| // Freeze the enum if required | ||
| let res = superEn; | ||
| if (!(options === null || options === void 0 ? void 0 : options.noFreeze)) { | ||
| res = Object_freeze(superEn); | ||
| Object_freeze(iterationKeys); | ||
| Object_freeze(values); | ||
| Object_freeze(entries); | ||
| } | ||
| return res; | ||
| }; | ||
| return init(options); | ||
| } | ||
| const superenum = fromObject; | ||
| exports.superenum = superenum; | ||
| superenum.fromObject = fromObject; | ||
| superenum.fromArray = fromArray; | ||
| //# sourceMappingURL=superenum.js.map |
| {"version":3,"file":"superenum.js","sourceRoot":"","sources":["../../src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AAC;QAEF,qBAAqB,CACnB,OAAO,EACP,MAAM,CAAC,QAAQ,EACf,aAAa,CACX;YACE,KAAK,EAAE,aAAa;SACrB,EACD,qBAAqB,CACtB,CACF,CAAC;QAEF,qBAAqB,CACnB,OAAO,EACP,QAAQ,EACR,aAAa,CACX;YACE,KAAK,EAAE,GAAG,EAAE,CAAC,MAAM;SACpB,EACD,qBAAqB,CACtB,CACF,CAAC;QAEF,qBAAqB,CACnB,OAAO,EACP,MAAM,EACN,aAAa,CACX;YACE,KAAK,EAAE,GAAG,EAAE,CAAC,aAAa;SAC3B,EACD,qBAAqB,CACtB,CACF,CAAC;QAEF,qBAAqB,CACnB,OAAO,EACP,SAAS,EACT,aAAa,CACX;YACE,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO;SACrB,EACD,qBAAqB,CACtB,CACF,CAAC;QAEF,8BAA8B;QAC9B,IAAI,GAAG,GAAG,OAAO,CAAC;QAClB,IAAI,CAAC,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,CAAA,EAAE,CAAC;YACvB,GAAG,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;YAC7B,aAAa,CAAC,aAAa,CAAC,CAAC;YAC7B,aAAa,CAAC,MAAM,CAAC,CAAC;YACtB,aAAa,CAAC,OAAO,CAAC,CAAC;QACzB,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;IAEF,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;AACvB,CAAC;AAED,MAAM,SAAS,GAAc,UAAiB,CAAC;AAItC,8BAAS;AAHlB,SAAS,CAAC,UAAU,GAAG,UAAU,CAAC;AAClC,SAAS,CAAC,SAAS,GAAG,SAAS,CAAC"} |
| /* | ||
| Copyright ©2022-24 Ncoderz Ltd | ||
| Redistribution and use in source and binary forms, with or without modification, are permitted provided that the | ||
| following conditions are met: | ||
| 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following | ||
| disclaimer. | ||
| 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the | ||
| following disclaimer in the documentation and/or other materials provided with the distribution. | ||
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, | ||
| INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
| SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, | ||
| WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE | ||
| USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| */ | ||
| function fromArray(arr, options) { | ||
| if (!Array.isArray(arr)) | ||
| arr = []; | ||
| const enumeration = arr.reduce((acc, v) => { | ||
| acc[`${v}`] = v; | ||
| return acc; | ||
| }, {}); | ||
| // Default the iteration keys to be the passed in arr if not set | ||
| if (!options || (options && !options.iterationKeys)) { | ||
| options = Object.assign({}, options); | ||
| options.iterationKeys = arr; | ||
| } | ||
| return fromObject(enumeration, options); | ||
| } | ||
| function fromObject(enumeration, options) { | ||
| var _a; | ||
| // For reducing code size when minified | ||
| const Object_freeze = Object.freeze; | ||
| const Object_defineProperty = Object.defineProperty; | ||
| const Object_assign = Object.assign; | ||
| const definePropertyOptions = { | ||
| enumerable: false, | ||
| }; | ||
| const keyValueMap = new Map(); | ||
| const valueKeyMap = new Map(); | ||
| const lcKeyValueMap = new Map(); | ||
| const lcValueKeyMap = new Map(); | ||
| const metadataMap = new Map(); | ||
| const iterationKeys = ((_a = options === null || options === void 0 ? void 0 : options.iterationKeys) !== null && _a !== void 0 ? _a : Object.keys(enumeration)).map((k) => `${k}`); | ||
| // Fill keyValueMap and lcKeyValueMap | ||
| for (const [key, value] of Object.entries(enumeration)) { | ||
| // key must be a string since it's an object property | ||
| keyValueMap.set(key, value); | ||
| lcKeyValueMap.set(key.toLowerCase(), value); | ||
| } | ||
| // Fill valueKeyMap and lcValueKeyMap | ||
| for (const [key, value] of keyValueMap) { | ||
| // value might be a number, so much check | ||
| const lcValue = typeof value === 'string' ? value.toLowerCase() : value; | ||
| valueKeyMap.set(value, key); | ||
| lcValueKeyMap.set(lcValue, key); | ||
| } | ||
| const values = iterationKeys.map((k) => keyValueMap.get(k)); | ||
| const entries = iterationKeys.map((k) => [k, keyValueMap.get(k)]); | ||
| const init = (options) => { | ||
| let superEn = enumeration; | ||
| // If original object is not extensible, so we have to make a copy | ||
| if (!Object.isExtensible(enumeration)) { | ||
| superEn = Object_assign({}, enumeration); | ||
| } | ||
| function fromValue(value, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof value === 'string') { | ||
| return keyValueMap.get(lcValueKeyMap.get(value.toLowerCase())); | ||
| } | ||
| if (!valueKeyMap.has(value)) | ||
| return undefined; | ||
| return value; | ||
| } | ||
| function fromKey(key, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof key === 'string') { | ||
| return lcKeyValueMap.get(key.toLowerCase()); | ||
| } | ||
| return keyValueMap.get(`${key}`); | ||
| } | ||
| function keyFromValue(value, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.ignoreCase) && typeof value === 'string') { | ||
| return lcValueKeyMap.get(value.toLowerCase()); | ||
| } | ||
| return valueKeyMap.get(value); | ||
| } | ||
| function setMetadata(value, metadata, options) { | ||
| options; | ||
| const v = fromValue(value); | ||
| if (v != null) | ||
| metadataMap.set(v, metadata); | ||
| } | ||
| function getMetadata(value, options) { | ||
| options; | ||
| return metadataMap.get(value); | ||
| } | ||
| function valueIterator() { | ||
| let i = 0; | ||
| return { | ||
| // [Symbol.iterator]() { | ||
| // return this; | ||
| // }, | ||
| next: () => { | ||
| if (i < iterationKeys.length) { | ||
| return { value: keyValueMap.get(`${iterationKeys[i++]}`), done: false }; | ||
| } | ||
| return { | ||
| done: true, | ||
| }; | ||
| }, | ||
| }; | ||
| } | ||
| // Add helper functions to the enum but so they cannot be enumerated | ||
| Object_defineProperty(superEn, 'fromKey', Object_assign({ | ||
| value: fromKey, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'fromValue', Object_assign({ | ||
| value: fromValue, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'keyFromValue', Object_assign({ | ||
| value: keyFromValue, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'setMetadata', Object_assign({ | ||
| value: setMetadata, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'getMetadata', Object_assign({ | ||
| value: getMetadata, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, Symbol.iterator, Object_assign({ | ||
| value: valueIterator, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'values', Object_assign({ | ||
| value: () => values, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'keys', Object_assign({ | ||
| value: () => iterationKeys, | ||
| }, definePropertyOptions)); | ||
| Object_defineProperty(superEn, 'entries', Object_assign({ | ||
| value: () => entries, | ||
| }, definePropertyOptions)); | ||
| // Freeze the enum if required | ||
| let res = superEn; | ||
| if (!(options === null || options === void 0 ? void 0 : options.noFreeze)) { | ||
| res = Object_freeze(superEn); | ||
| Object_freeze(iterationKeys); | ||
| Object_freeze(values); | ||
| Object_freeze(entries); | ||
| } | ||
| return res; | ||
| }; | ||
| return init(options); | ||
| } | ||
| const superenum = fromObject; | ||
| superenum.fromObject = fromObject; | ||
| superenum.fromArray = fromArray; | ||
| export { superenum }; | ||
| //# sourceMappingURL=superenum.js.map |
| {"version":3,"file":"superenum.js","sourceRoot":"","sources":["../../src/superenum.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;EAqBE;AAoRF,SAAS,SAAS,CAAC,GAAQ,EAAE,OAAqB;IAChD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAAE,GAAG,GAAG,EAAE,CAAC;IAElC,MAAM,WAAW,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,GAAQ,EAAE,CAAM,EAAE,EAAE;QAClD,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QAChB,OAAO,GAAG,CAAC;IACb,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,gEAAgE;IAChE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;QACpD,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACrC,OAAO,CAAC,aAAa,GAAG,GAAG,CAAC;IAC9B,CAAC;IAED,OAAO,UAAU,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAC1C,CAAC;AAED,SAAS,UAAU,CAAC,WAAgB,EAAE,OAAqB;;IACzD,uCAAuC;IACvC,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,MAAM,qBAAqB,GAAG,MAAM,CAAC,cAAc,CAAC;IACpD,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,MAAM,qBAAqB,GAAG;QAC5B,UAAU,EAAE,KAAK;KAClB,CAAC;IAEF,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;IAClD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;IAClD,MAAM,aAAa,GAAG,IAAI,GAAG,EAAsB,CAAC;IACpD,M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EnumKey = string; | ||
| /** | ||
| * Enum values | ||
| */ | ||
| export type EnumValue = string | number; | ||
| /** | ||
| * Array Enum declaration | ||
| */ | ||
| export type ArrayEnum<V extends EnumValue> = V[]; | ||
| /** | ||
| * Object enum declaration | ||
| */ | ||
| export type ObjectEnum<K extends EnumKey, V extends EnumValue> = { | ||
| [key in K]: V; | ||
| }; | ||
| /** | ||
| * Convert an ArrayEnum type to an ObjectEnum | ||
| */ | ||
| export type ArrayEnumToObjectEnum<T extends ReadonlyArray<EnumValue>> = { | ||
| [K in T extends ReadonlyArray<infer U> ? U : never]: T extends ReadonlyArray<infer U> ? U : never; | ||
| }; | ||
| /** | ||
| * Get the type of an enum from a superenum, removing the {@link EnumExtensions} from the type | ||
| */ | ||
| export type EnumType<T> = T[keyof Omit<T, keyof EnumExtensions<EnumValue>>]; | ||
| /** | ||
| * Options for the {@link Superenum} and {@link Superenum.fromArray} functions | ||
| */ | ||
| export interface EnumOptions { | ||
| iterationKeys?: ArrayEnum<EnumValue>; | ||
| noFreeze?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link EnumExtensions.fromValue} function | ||
| */ | ||
| export interface FromValueOptions { | ||
| /** | ||
| * Ignore case when validating the enum value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link EnumExtensions.fromKey} function | ||
| */ | ||
| export interface FromKeyOptions { | ||
| /** | ||
| * Ignore case when getting the enum value from the key | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link EnumExtensions.keyFromValue} function | ||
| */ | ||
| export interface KeyFromValueOptions { | ||
| /** | ||
| * Ignore case when getting the enum key from the value | ||
| */ | ||
| ignoreCase?: boolean; | ||
| } | ||
| /** | ||
| * Options for the {@link EnumExtensions.setMetadata} function | ||
| */ | ||
| export interface SetMetadataOptions { | ||
| } | ||
| /** | ||
| * Options for the {@link EnumExtensions.getMetadata} function | ||
| */ | ||
| export interface GetMetadataOptions { | ||
| } | ||
| export interface EnumExtensions<V extends EnumValue> { | ||
| /** | ||
| * Validate an enum value, returning the value if valid, otherwise undefined. | ||
| * | ||
| * Since a superenum is just the value, then all this function does is check to see if the value exists, and if | ||
| * so returns it, otherwise it returns undefined. | ||
| * | ||
| * Note: If the enum has duplicate values (or duplicate values when lower-cased if | ||
| * {@link FromValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to validate | ||
| * @param options - options for the function | ||
| * @returns the enum value, or undefined if the value cannot be matched to the enum | ||
| */ | ||
| fromValue(value: unknown | null | undefined, options?: FromValueOptions): V | undefined; | ||
| /** | ||
| * Get an enum value from its key, returning the value if key valid, otherwise undefined. | ||
| * | ||
| * Note: If the enum has duplicate keys when lower-cased if | ||
| * {@link FromKeyOptions.ignoreCase} is true, the data returned when when keys clash will be indeterminate. | ||
| * | ||
| * @param key - the enum key to convert to enum value | ||
| * @param options - options for the function | ||
| * @returns the enum represented by the key, or undefined if the key cannot be matched to the enum | ||
| */ | ||
| fromKey(key: EnumKey | number | null | undefined, options?: FromKeyOptions): V | undefined; | ||
| /** | ||
| * Get an enum key from its value, returning the key if value valid, otherwise undefined. | ||
| * | ||
| * Note: If the enum has duplicate values (or duplicate values when lower-cased if | ||
| * {@link KeyFromValueOptions.ignoreCase} is true), the data returned when when values clash will be indeterminate. | ||
| * | ||
| * @param value - the enum value to convert to enum key | ||
| * @param options - options for the function | ||
| * @returns the enum key represented by the value, or undefined if the value cannot be matched to the enum | ||
| */ | ||
| keyFromValue(value: unknown | null | undefined, options?: KeyFromValueOptions): string | undefined; | ||
| /** | ||
| * Store metadata for an enum value. If value is not valid, the metadata will not be stored. | ||
| * | ||
| * @param value - the value for which to store metadata | ||
| * @param metadata - the metadata to store | ||
| * @param options - options for the function | ||
| * @returns true if the metadata was associated with the value, otherwise false | ||
| */ | ||
| setMetadata<M>(value: V | null | undefined, metadata: M, options?: SetMetadataOptions): boolean; | ||
| /** | ||
| * Retrieve metadata that was stored against an enum value. | ||
| * | ||
| * If no metadata is found, or the value is invalid, undefined will be returned. | ||
| * | ||
| * @param value - the value for which to retrieve metadata | ||
| * @param options - options for the function | ||
| * @returns the metadata associated with the enum value | ||
| */ | ||
| getMetadata<M>(value: V | null | undefined, options?: GetMetadataOptions): M | undefined; | ||
| /** | ||
| * Get an array of the enum values. | ||
| * | ||
| * Note: Item order is guaranteed unless the enum is initialised using {@link Superenum} or | ||
| * {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will | ||
| * follow the rules of the JavaScript engine which may vary. In order to guarantee the item order | ||
| * in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array | ||
| * of keys to {@link EnumOptions.iterationKeys} to represent the desired item order. | ||
| * | ||
| * https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| values(): readonly V[]; | ||
| /** | ||
| * Get an array of the enum keys. | ||
| * | ||
| * Note: Item order is guaranteed unless the enum is initialised using {@link Superenum} or | ||
| * {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will | ||
| * follow the rules of the JavaScript engine which may vary. In order to guarantee the item order | ||
| * in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array | ||
| * of keys to {@link EnumOptions.iterationKeys} to represent the desired item order. | ||
| * | ||
| * https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| keys(): readonly EnumKey[]; | ||
| /** | ||
| * Get an array of the enum entries. | ||
| * | ||
| * Note: Item order is guaranteed unless the enum is initialised using {@link Superenum} or | ||
| * {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will | ||
| * follow the rules of the JavaScript engine which may vary. In order to guarantee the item order | ||
| * in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array | ||
| * of keys to {@link EnumOptions.iterationKeys} to represent the desired item order. | ||
| * | ||
| * https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| entries(): readonly [EnumKey, V][]; | ||
| /** | ||
| * An iterator that iterates the enum values. | ||
| * | ||
| * Note: Iteration order is guaranteed unless the enum is initialised using {@link Superenum} or | ||
| * {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will | ||
| * follow the rules of the JavaScript engine which may vary. In order to guarantee iteration order | ||
| * in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array | ||
| * of keys to {@link EnumOptions.iterationKeys} to represent the desired iteration order. | ||
| * | ||
| * https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order | ||
| * | ||
| * @returns iterator over the enum values | ||
| */ | ||
| [Symbol.iterator](): IterableIterator<V>; | ||
| } | ||
| /** | ||
| * Interface to manage superenums | ||
| */ | ||
| export interface Superenum { | ||
| /** | ||
| * Create a superenum from a plain JavaScript object. | ||
| * | ||
| * Alias of {@link Superenum.fromObject}. | ||
| * | ||
| * @param enumeration - the plain JavaScript object enum to enhance | ||
| * @param options - options for the enum enhancement | ||
| * @returns the plain object enum converted to a superenum | ||
| */ | ||
| <K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>>(enumeration: T, options?: EnumOptions): Readonly<T> & EnumExtensions<EnumType<T>>; | ||
| /** | ||
| * Create a superenum from a plain JavaScript object. | ||
| * | ||
| * The plain JavaScript object will be enhanced with {@link EnumExtensions}. | ||
| * | ||
| * Note: Item / iteration order is guaranteed unless the enum is initialised using {@link Superenum} or | ||
| * {@link Superenum.fromObject} and it contains keys which can be converted to integers. In this case it will | ||
| * follow the rules of the JavaScript engine which may vary. In order to guarantee the item / iteration order | ||
| * in the case of integer keys, use {@link Superenum.fromArray} to initialise the enum, or pass in an array | ||
| * of keys to {@link EnumOptions.iterationKeys} to represent the desired item / iteration order. | ||
| * | ||
| * Note: If the object has duplicate values, or duplicate keys or values when lower-cased, the initialisation will | ||
| * still succeed. However, the behaviour of | ||
| * {@link EnumExtensions.fromValue}, | ||
| * {@link EnumExtensions.fromKey}, | ||
| * {@link EnumExtensions.keyFromValue} | ||
| * will be indeterminate in cases where the keys / values clash. | ||
| * | ||
| * @param enumeration - the plain JavaScript object enum to enhance | ||
| * @param options - options for the enum enhancement | ||
| * @returns the plain object enum converted to a superenum | ||
| */ | ||
| fromObject<K extends EnumKey, V extends EnumValue, T extends ObjectEnum<K, V>>(enumeration: T, options?: EnumOptions): Readonly<T> & EnumExtensions<EnumType<T>>; | ||
| /** | ||
| * Create a superenum from a plain JavaScript array. | ||
| * | ||
| * The array will be converted to a plain JavaScript object will be enhanced with {@link EnumExtensions}. | ||
| * | ||
| * Note: Iteration order is guaranteed to be that of the items in the array. A different iteration order can be | ||
| * specified using {@link EnumOptions.iterationKeys} to represent the desired iteration order. | ||
| * | ||
| * Note: If the array has duplicate values, the initialisation will not fail. Instead the duplicate values will | ||
| * be ignored and the resultant enum will contain just one of the values. | ||
| * | ||
| * Note: If the array has duplicate values when lower-cased, the data returned when | ||
| * calling {@link EnumExtensions.fromKey} and {@link EnumExtensions.keyFromValue} with | ||
| * *ignoreCase* set will be indeterminate for duplicate keys / values. | ||
| * | ||
| * @param enumeration - the plain JavaScript array to convert and enhance | ||
| * @param options - options for the enum enhancement | ||
| * @returns the plain array enum converted to a superenum | ||
| */ | ||
| fromArray<V extends EnumValue, T extends ArrayEnum<V>>(enumeration: T, options?: EnumOptions): Readonly<ArrayEnumToObjectEnum<T>> & EnumExtensions<EnumType<ArrayEnumToObjectEnum<T>>>; | ||
| } | ||
| declare const superenum: Superenum; | ||
| export { superenum }; | ||
| //# sourceMappingURL=superenum.d.ts.map |
| {"version":3,"file":"superenum.d.ts","sourceRoot":"","sources":["../../src/superenum.ts"],"names":[],"mappings":"AAyBA;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC;AAE7B;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAExC;;GAEG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EAAE,WAAW,GACpB,QAAQ,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IAE7C;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,UAAU,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,EAC3E,WAAW,EAAE,CAAC,EACd,OAAO,CAAC,EAAE,WAAW,GACpB,QAAQ,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IAE7C;;;;;;;;;;;;;;;;;;OAkBG;IACH,SAAS,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,EACnD,WAAW,EAAE,CAAC,EACd,OAAO,CAAC,EAAE,WAAW,GACpB,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAC5F;AAmOD,QAAA,MAAM,SAAS,EAAE,SAA6B,CAAC;AAI/C,OAAO,EAAE,SAAS,EAAE,CAAC"} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
112847
71.49%16
-36%25
127.27%2
-33.33%428
14.13%0
-100%Yes
NaN566
-0.7%1
Infinity%