How to gracefully use enumeration definitions in JS


How to use enumerations gracefully in JS

Why use enumeration

  • De magic number
  • Enumeration semantics
  • Definition integration: enumeration values and enumeration descriptions are written together and are not scattered
  • Easy to use: no additional filter is required

How to explain

  • De magic number

See the following code

// bad
< span V-IF = "status = = 0" > under approval</span>
< span v-else-if = "status = = 1" > approved</span>
< span v-else-if = "status = = 2" > failed approval</span>
// bad
if(status===1 || status === 2){

The maintenance of this code is nothing more than understanding12What meaning does this number represent, which makes it difficult to maintain and understand business logic

  • Enumeration semantics

We need to reform it

const STATUS = {

if(status===STATUS.WAIT || status === STATUS.ERROR){

Through simple transformation, we have a new way to use it. We define an object in advance, and each key corresponds to the relevant value. In code writing, we can easily understand that the state is equal toWAIT,ERROR, i.e. wait or fail

But this is not simple and convenient enough. For example, we need to get the status as1Description when

We can do this:

    [status. Wait]: 'being approved',
    [status. Error]: 'approval failed'

Specific use


However, it faces a new problem. Each defined value and description must be rewritten separately, resulting in a lot of repetitive work

  • Easy to use: no additional filter is required

We customize onecreateEnummethod

 *Enumeration definition tool
 * const STATUS = createEnum({
 *     AUDIT_ Wait: [1, 'being approved'],
 *     AUDIT_ Pass: [2, 'approved']
 * })
 *Get enumeration value: status.audit_ WAIT
 *Get enumeration Description: status. Getdesc ('audit)_ WAIT')
 *Get description by enumerating values: status.getdescfromvalue (status. Wait)
export default function createEnum(definition) {
  const strToValueMap = {}
  const numToDescMap = {}
  for (const enumName of Object.keys(definition)) {
    const [value, desc] = definition[enumName]
    strToValueMap[enumName] = value
    numToDescMap[value] = desc
  return {
    getDesc(enumName) {
      return (definition[enumName] && definition[enumName][1]) || ''
    getDescFromValue(value) {
      return numToDescMap[value] || ''

Let’s rewrite the above case with a tool class

const STATUS = createEnum({
    AUDIT_ Wait: [1, 'being approved'],
    AUDIT_ Pass: [2, 'approved']
if(status===STATUS.WAIT || status === STATUS.ERROR){
<p>Current status: {status. Getdescfromvalue (status)}</p>
<p>Descriptions can also be obtained by enumerating names: {status. Getdesc ('auditing ')}</p>


becausejsWithout the concept of enumeration, with the help ofJAVAIdea, we write to create enumeration methods

This article starts with how to use enumeration definitions in JS