Enums in Elm

JavaScript Example

Our enum type ServerState has an underlying integer type.

The possible values for ServerState are defined as constants. In JavaScript, we can use an object to emulate enum-like behavior.

By implementing a toString method, values of ServerState can be printed out or converted to strings.

If we have a value of type number, we need to ensure type validation within our function to provide some degree of type safety for enums.

const ServerState = {
  IDLE: 0,
  CONNECTED: 1,
  ERROR: 2,
  RETRYING: 3,
  
  toString: function(state) {
    const stateNames = {
      0: 'idle',
      1: 'connected',
      2: 'error',
      3: 'retrying'
    };
    return stateNames[state];
  }
};

function main() {
  let ns = transition(ServerState.IDLE);
  console.log(ServerState.toString(ns));

  let ns2 = transition(ns);
  console.log(ServerState.toString(ns2));
}

function transition(s) {
  switch (s) {
    case ServerState.IDLE:
      return ServerState.CONNECTED;
    case ServerState.CONNECTED:
    case ServerState.RETRYING:
      // Suppose we check some predicates here to determine the next state...
      return ServerState.IDLE;
    case ServerState.ERROR:
      return ServerState.ERROR;
    default:
      throw new Error(`unknown state: ${s}`);
  }
}

main();

To run the program, save the code into a file, e.g., enums.js, and use node to execute it.

$ node enums.js
connected
idle

In this example, we have shown how to define and use enum-like structures in JavaScript. Now that we can run and understand basic JavaScript programs, let’s learn more about the language.