9.7.79 • Published 1 year ago

@zitterorg/maiores-commodi-ea v9.7.79

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Easy to use, Symbol-based enum implementation

Just list keys you need and enumerate tag function will create an object with corresponding properties and unique values for your convenience.

Installation

Install with npm:

npm install @zitterorg/maiores-commodi-ea

Install with yarn:

yarn add @zitterorg/maiores-commodi-ea

Import where you need it:

import enumerate from '@zitterorg/maiores-commodi-ea';

or require for CommonJS:

const enumerate = require('@zitterorg/maiores-commodi-ea');

How to use

Example 1:

const { FOOT, METER } = enumerate`FOOT METER`;

const convertToFeet = (value, unit = FOOT) => {
  if (unit === METER) {
    return value * 3.281;
  }
  return value;
};

console.log(`${convertToFeet(5)} feet`); // 5 feet
console.log(`${convertToFeet(2, METER)} feet`); // 6.562 feet

Example 2:

const STAR_WARS = enumerate`I II III IV V VI`;

const getEpisodeName = episode => {
  const { I, II, III, IV, V, VI } = STAR_WARS;
  switch (episode) {
    case I:
      return 'The Phantom Menace';
    case II:
      return 'Attack of the Clones';
    case III:
      return 'Revenge of the Sith';
    case IV:
      return 'A New Hope';
    case V:
      return 'The Empire Strikes Back';
    case VI:
      return 'Return of the Jedi';
    default:
      return 'Unknown';
  }
};

console.log(getEpisodeName(STAR_WARS.III)); // Revenge of the Sith
console.log(getEpisodeName(STAR_WARS.IV)); // A New Hope
console.log(getEpisodeName(STAR_WARS.X)); // Error: Invalid enum key: X

Primitive enum converters

By default enumerate converts values to Symbols:

console.log(enumerate`FOOT METER`); // Enum { FOOT: Symbol(FOOT), METER: Symbol(METER) }

You can change this behavior by specifying an appropriate converter:

console.log(enumerate(String)`FOOT METER`); // Enum { FOOT: 'FOOT', METER: 'METER' }
console.log(enumerate(Number)`ZERO ONE TWO`); // Enum { ZERO: 0, ONE: 1, TWO: 2 }
// or
const enumString = enumerate(String);
const enumNumber = enumerate(Number);
console.log(enumString`FOOT METER`); // Enum { FOOT: 'FOOT', METER: 'METER' }
console.log(enumNumber`ZERO ONE TWO`); // Enum { ZERO: 0, ONE: 1, TWO: 2 }

Advanced enum converters

There are several advanced converters also available.

const { LowerCase, UpperCase, Prefix, Increment } = enumerate;

console.log(enumerate(LowerCase)`
VALUE1
VALUE2
VALUE3
`); // Enum { VALUE1: 'value1', VALUE2: 'value2', VALUE3: 'value3' }

console.log(enumerate(UpperCase)`
value1
value2
value3
`); // Enum { value1: 'VALUE1', value2: 'VALUE2', value3: 'VALUE3' }

console.log(enumerate(Prefix('value|'))`x y z`); // Enum { x: 'value|x', y: 'value|y', z: 'value|z' }
// or as a shortcut
console.log(enumerate('value|')`x y z`); // Enum { x: 'value|x', y: 'value|y', z: 'value|z' }

console.log(enumerate(Increment(10))`
VALUE1
VALUE2
VALUE3
`); // Enum { VALUE1: 10, VALUE2: 20, VALUE3: 30 }
// or as a shortcut
console.log(enumerate(10)`VALUE1 VALUE2 VALUE3`); // Enum { VALUE1: 10, VALUE2: 20, VALUE3: 30 }

// the second argument here is a start value (equals to the first argument if not specified)
console.log(enumerate(Increment(10, 19))`
VALUE1
VALUE2
VALUE3
`); // Enum { VALUE1: 19, VALUE2: 29, VALUE3: 39 }

Customization

Or you can implement your custom converter:

const customEnum = enumerate((acc, item) => {
  acc[`-${item}-`] = `-${(Object.keys(acc).length + 1) * 10}-`;
  return acc;
});

console.log(customEnum`
  CODE1
  CODE2
  CODE3
`); // Enum { '-CODE1-': '-10-', '-CODE2-': '-20-', '-CODE3-': '-30-' }

But remember that only default behavior guarantees global uniqueness of enumerated values.

enumerate.isEnum()

You can also check if the given object is a enum or not.

console.log(enumerate.isEnum({ a: 1, b: 2, c: 3 })); // false
console.log(enumerate.isEnum(enumerate`a b c`)); // true

Type-safety and IntelliSense (code completion)

The package includes a TypeScript Declaration File and supports VS Code IntelliSense features.

But there is one caveat. In order to achieve full type safety you have to use a bit different syntax. Unfortunately. So, instead of using enumerate() directly as a tag function you can use enumerate.ts() function.

Compare

versus

For example

enumerate.ts('ZERO ONE TWO', Number); // Enum { ZERO: 0, ONE: 1, TWO: 2 }

does exactly the same as

enumerate(Number)`ZERO ONE TWO`; // Enum { ZERO: 0, ONE: 1, TWO: 2 }

but it allows TypeScript to recognize the result type.

The reason of why we cannot use enumerate directly is that there is a long-standing TypeScript issue with TemplateStringArray being incorrectly typed and, as result, not being able to be parameterized.

Notes

  • Be careful adding new items to an existing numeric enum. Always append them to the end of the list to avoid changing previous item values.
  • Requires TypeScript 4.8+ for best type safety features support.
queuepropertiesio-tsArray.prototype.flatMapObject.keysprotocol-buffersoffsetsliceformworkerObject.assignmatchesstreamsigtermassertscoercibleobjpushcacheinstallerbannerreacteslintUint8ArrayindicatorrapidECMAScript 2023setMapStreamparentpredictablefastxtermbrowsernamesjwtArray.prototype.filterqueueMicrotaskrecursiveiteratorirqURLSearchParamsregular expressionsargvinterruptsArray.prototype.findLastebscore-jsmruObservablesmimeECMAScript 2019fsMicrosoftcallboundagentObject.valuesRegExp#flagseventsnpmextensionrequestarraydependency managerReactiveXframeworkhashstarteruuidexpressioncloudsearchs3gradients css3error-handlingUint16ArraysidekeyWebSocketdeepfullFloat64Arraygradients css__proto__ES2022passwordhttpscode pointsvpccolumnsrouterassertionelbdynamodbcommand-lineECMAScript 5patchgetintrinsicschemelivefunctioneventDispatcherES6descriptionargparsesameValueZeropromisesstreamschineseloadingvariablesformswgetclass-validatorphonedatastructurequoteaccessibilityfunctionstoolkittoobjectruntimeenumerablecalltapsortcss lessString.prototype.matchAllArray.prototype.findLastIndextostringtaggetterdirsignalsbcryptbusydeepclonesortedes7bootstrap cssconcatMapauthinferencebyteLengthsomebrowserlistYAMLclassnamestslibiterationawesomesauceeslint-pluginstyled-componentstypeerrorECMAScript 2021pruneArrayBuffergetOwnPropertyDescriptorshebanggdprmimetypesrmparentscreatetoolsfastcopybyteOffsetjsscheme-validationdependenciespackage.jsonguidchromiumspinnersreduxjestECMAScript 6TypedArraynodeexpressintrinsicmacosArray.prototype.containscss nestinges5weakmapFloat32Arraydeep-copydomsharedarraybufferSetthrottlerdsswfpostcsswebflattentrimRightcollection.es6bytefinduppipedefinePropertyfastclonelockfileerrorstatefseventsformattingECMAScript 2020compile lessbindgetoptsharedfixed-widthcloudfrontwatchFilemergematchutilchaiES2016outputmkdirphelpersserializationtraverseECMAScript 2015optionhasreact-hooksunicodewrapmaptyped arrayjQuerytrimreplayworkspace:*compilerless.jsfullwidthmetadatatypescriptdayjsprotoeslintconfigserializeStyleSheetpreprocessorjapaneseyamlexecfile systemautoprefixerflatMapreadrm -fremojies6ReactiveExtensionssymbolsinputescapelazydeep-clonecjkoptimistproxyeventEmitterrfc4122endpointArray.prototype.includesmonorepolastwindowssyntaxloggerjsonconsolenested cssenvprefixhandlerszerovalidFunction.prototype.nameterminaltypanionexitasyncBigInt64Arraypostcss-plugingenericsshiminvariantdifftrimEndkeyseast-asian-width256apisnsreusepackagesstreams2hasOwnPropertytrimStarthigher-orderisConcatSpreadablegetPrototypeOfWeakMapappemrimmutablesymlinkbreaktypesajvquerystringRegExp.prototype.flagswaitidwalkingPromisevaluedatawritableES3ArrayobjectwhatwglintspeedcharactersES2019look-upReflect.getPrototypeOfdeterministiccollectiontypedes-shim APIsigintes2015arraybufferclilessCSSUint32Arrayprocessexit-codeseskinesispropforEachtakeflatrequireansiES2015jsdomtypedarrayratelimitsetteremitlinuxhasOwnownprettyi18nxhrpicomatchajaxreact-hook-formURLcryptequalperformantjsxtypedarrayscheckurlObject.isbootstrap less_.extendjoibddawsjsonpathinternalvestcallbindgetArrayBuffer#slicepackage managerprivate datatc39visualstylescolorfromtestingomitgroupworkflowlimitedcall-boundes2017bluebirdrangeerrorwordbreakES8ES2023functionalbundlerES7dataViewcompareTypeScriptfigletestreefilterSymbol.toStringTagcontainstestviewArray.prototype.flatmixinsnumberbufferses8performanceloggingopenhas-ownfindLastES
@zitterorg/amet-porro-impedit@zitterorg/amet-minus@zitterorg/amet-vero-laboriosam@zitterorg/amet-accusamus@zitterorg/animi-accusantium-similique@zitterorg/animi-atque@zitterorg/aliquid-ducimus-provident@zitterorg/asperiores-consectetur@zitterorg/architecto-dolore@zitterorg/asperiores-molestias@zitterorg/aut-fugit@zitterorg/earum-harum@zitterorg/doloribus-itaque@zitterorg/doloribus-quidem-enim@zitterorg/hic-suscipit@zitterorg/harum-ratione@zitterorg/hic-dicta@zitterorg/nemo-dolorem@zitterorg/necessitatibus-doloremque@zitterorg/natus-tempora@zitterorg/nemo-tenetur@zitterorg/numquam-itaque@zitterorg/pariatur-ad@zitterorg/perferendis-id@zitterorg/quaerat-error-quae@zitterorg/quasi-corrupti-voluptates@zitterorg/quas-in-suscipit@zitterorg/qui-dicta@zitterorg/quas-autem@zitterorg/quisquam-distinctio-veritatis@zitterorg/quis-maxime@zitterorg/quod-veritatis@zitterorg/ab-fugiat-impedit@zitterorg/a-in@zitterorg/consequatur-eius@zitterorg/blanditiis-esse-iusto@zitterorg/corporis-sit@zitterorg/cupiditate-fugiat-culpa@zitterorg/corrupti-animi-beatae@zitterorg/corporis-ut-consectetur@zitterorg/cum-commodi@zitterorg/cum-non@zitterorg/dolor-laboriosam@zitterorg/dolor-nostrum-porro@zitterorg/dolore-quas@zitterorg/distinctio-perferendis@zitterorg/eum-expedita@zitterorg/fugit-ex-neque@zitterorg/inventore-facere@zitterorg/incidunt-voluptas@zitterorg/ipsum-magnam@zitterorg/itaque-nesciunt-voluptatibus@zitterorg/itaque-sapiente-similique@zitterorg/itaque-ab@zitterorg/occaecati-beatae@zitterorg/quia-sapiente@zitterorg/quibusdam-numquam@zitterorg/rem-iure@zitterorg/repellat-ut@zitterorg/repudiandae-blanditiis@zitterorg/reprehenderit-soluta-ad@zitterorg/repellendus-impedit-repellendus@zitterorg/repudiandae-nihil-architecto@zitterorg/saepe-eos@zitterorg/sint-veritatis@zitterorg/tempore-debitis-minima@zitterorg/sit-expedita@zitterorg/totam-quos-dolorem@zitterorg/unde-exercitationem@zitterorg/velit-dicta@zitterorg/veritatis-repellat-debitis@zitterorg/voluptate-voluptatem@zitterorg/accusantium-quam@zitterorg/adipisci-ipsum@zitterorg/adipisci-autem@zitterorg/accusamus-quos-consequuntur@zitterorg/aperiam-nisi@zitterorg/consequuntur-perspiciatis@zitterorg/corporis-architecto@zitterorg/consequuntur-illum-corrupti@zitterorg/delectus-nisi-impedit@zitterorg/delectus-est@zitterorg/dolores-perspiciatis-rem@zitterorg/dolores-debitis@zitterorg/doloremque-aspernatur-molestias@zitterorg/dolores-consequatur@zitterorg/doloremque-sed@zitterorg/expedita-quasi@zitterorg/explicabo-iure@zitterorg/facere-id@zitterorg/illo-perspiciatis-animi@zitterorg/laudantium-rerum@zitterorg/iure-ut@zitterorg/magni-fugit@zitterorg/libero-vitae-at@zitterorg/molestias-in@zitterorg/mollitia-laborum-nesciunt@zitterorg/modi-non-tenetur@zitterorg/molestiae-soluta@zitterorg/nostrum-porro
9.7.79

1 year ago

9.7.76

1 year ago

9.7.75

1 year ago

9.7.78

1 year ago

9.7.77

1 year ago

9.6.74

1 year ago

9.6.75

1 year ago

9.6.73

1 year ago

8.6.73

1 year ago

8.6.72

1 year ago

8.6.71

1 year ago

8.6.67

1 year ago

8.6.69

1 year ago

8.6.68

1 year ago

8.6.70

1 year ago

6.5.55

1 year ago

6.4.43

1 year ago

6.5.54

1 year ago

6.4.42

1 year ago

6.5.57

1 year ago

6.4.45

1 year ago

6.5.56

1 year ago

6.4.44

1 year ago

6.5.59

1 year ago

6.4.47

1 year ago

6.5.58

1 year ago

6.4.46

1 year ago

6.4.49

1 year ago

6.4.48

1 year ago

6.6.60

1 year ago

6.5.51

1 year ago

6.5.50

1 year ago

6.5.53

1 year ago

6.4.41

1 year ago

6.5.52

1 year ago

6.4.40

1 year ago

6.6.59

1 year ago

6.5.49

1 year ago

7.6.62

1 year ago

7.6.61

1 year ago

7.6.60

1 year ago

7.6.66

1 year ago

7.6.65

1 year ago

7.6.64

1 year ago

7.6.63

1 year ago

7.6.67

1 year ago

5.3.40

1 year ago

5.4.40

1 year ago

5.3.39

1 year ago

5.3.38

1 year ago

5.3.37

1 year ago

5.3.36

1 year ago

5.3.35

1 year ago

5.3.34

1 year ago

4.3.34

1 year ago

4.3.31

1 year ago

4.3.33

1 year ago

4.3.32

1 year ago

4.2.31

1 year ago

3.2.29

1 year ago

4.2.29

1 year ago

4.2.30

1 year ago

3.2.24

1 year ago

3.2.26

1 year ago

3.2.25

1 year ago

3.2.28

1 year ago

3.2.27

1 year ago

2.1.24

1 year ago

2.0.24

1 year ago

2.2.24

1 year ago

2.0.22

1 year ago

2.0.23

1 year ago

2.0.20

1 year ago

2.0.21

1 year ago

2.0.19

1 year ago

2.0.18

1 year ago

2.0.17

1 year ago

2.0.15

1 year ago

2.0.16

1 year ago

2.0.14

1 year ago

2.0.13

1 year ago

2.0.12

1 year ago

2.0.11

1 year ago

2.0.10

1 year ago

2.0.9

1 year ago

2.0.8

1 year ago

2.0.7

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago