1. enumify
A JavaScript library that helps with the enum pattern. Also supports TypeScript.
enumify
Package: enumify
Created by: rauschma
Last modified: Fri, 17 Jun 2022 06:24:19 GMT
Version: 2.0.0
License: MIT
Downloads: 78,541
Repository: https://github.com/rauschma/enumify

Install

npm install enumify
yarn add enumify

Enumify

A JavaScript library that helps with the enum pattern. Also supports TypeScript.

Installation:

 npm install enumify

Basic usage

   class Color extends Enumify {
    static red = new Color();
    static orange = new Color();
    static yellow = new Color();
    static green = new Color();
    static blue = new Color();
    static purple = new Color();
    static _ = this.closeEnum(); // TypeScript: Color.closeEnum()
  }

  // Instance properties
  assert.equal(
    Color.red.enumKey, 'red');
  assert.equal(
    Color.red.enumOrdinal, 0);
  
  // Prototype methods
  assert.equal(
    'Color: ' + Color.red, // .toString()
    'Color: Color.red');
  
  // Static `.enumKeys` and static `.enumValues`
  assert.deepEqual(
    Color.enumKeys,
    ['red', 'orange', 'yellow', 'green', 'blue', 'purple']);
  assert.deepEqual(
    Color.enumValues,
    [ Color.red, Color.orange, Color.yellow,
      Color.green, Color.blue, Color.purple ]);

  // Static `.enumValueOf()`
  assert.equal(
    Color.enumValueOf('yellow'),
    Color.yellow);
  
  // Iterability
  const result = [];
  const iterated = [...Color];
  for (const c of Color) {
    result.push('Color: ' + c);
  }
  assert.deepEqual(
    iterated, [
      Color.red,
      Color.orange,
      Color.yellow,
      Color.green,
      Color.blue,
      Color.purple,
    ]);

More examples

See:

  • ts/test/index_test.ts
  • ts/test/state.ts

Run tests like this (after compiling TypeScript, e.g. via npm run build):

npm t dist/test/index_test.js

RELATED POST

10 Must-Know Windows Shortcuts That Will Save You Time

10 Must-Know Windows Shortcuts That Will Save You Time

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Navigating AWS Networking: Essential Hacks for Smooth Operation

Navigating AWS Networking: Essential Hacks for Smooth Operation

Achieving Stunning Visuals with Unity's Global Illumination

Achieving Stunning Visuals with Unity's Global Illumination

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code