javascriptgoogle-apps-scriptenums

Enum in Google Scripts


If I understood correctly, there is no enum in Javascript/Google Scripts (I'm a Javascript novice, so I know just the basics of it). To overcome this, one can define a list of constants, like:

const COLUMNS_INDEXES
{
  FIRST_NAME: 1,
  LAST_NAME: 2,
  ADDRESS: 3
}

As suggested by this example, I need to define the columns indexes of various entries in a Spreadsheet, so I can access them via constants and have a more readable/editable code.

Needing to manually set every entry is quite annoying and, more important, prone to mistake. Also, when I need to insert a new column between two existing ones, I need to edit all the following entries (more annoying, more risk of errors). Example:

const COLUMNS_INDEXES
{
  FIRST_NAME: 1,
  NICKNAME: 2,
  LAST_NAME: 3,
  ADDRESS: 4
}

A good solution to this could have been to declare the list like this:

const COLUMNS_INDEXES
{
  FIRST_NAME: 1,
  LAST_NAME: FIRST_NAME + 1,
  ADDRESS: LAST_NAME + 1
}

This way when I insert a new entry I just need to edit a couple of lines, and all the following ones gets "automatically updated":

const COLUMNS_INDEXES
{
  FIRST_NAME: 1,
  NICKNAME: FIRST_NAME + 1,
  LAST_NAME: NICKNAME+ 1,
  ADDRESS: LAST_NAME + 1
}

Awfully, this syntax generates an error... Same if I fully reference the entries, like LAST_NAME: COLUMNS_INDEXES.FIRST_NAME + 1.

So, the question is: Is there a smart way to declare enums/consts without needing to set the value of every entry?


Solution

  • Consider the following sample script:

    Sample script 1:

    const COLUMNS_INDEXES = {
      FIRST_NAME: 1,
      get NICKNAME() { return this.FIRST_NAME + 1 },
      get LAST_NAME() { return this.NICKNAME + 1 },
      get ADDRESS() { return this.LAST_NAME + 1 },
    };
    
    console.log(COLUMNS_INDEXES.FIRST_NAME); // 1
    console.log(COLUMNS_INDEXES.NICKNAME); // 2
    console.log(COLUMNS_INDEXES.LAST_NAME); // 3
    console.log(COLUMNS_INDEXES.ADDRESS); // 4
    console.log(JSON.stringify(COLUMNS_INDEXES)); // {"FIRST_NAME":1,"NICKNAME":2,"LAST_NAME":3,"ADDRESS":4}

    Sample script 2:

    const keys = ["FIRST_NAME", "NICKNAME", "LAST_NAME", "ADDRESS"];
    const COLUMNS_INDEXES = keys.reduce((o, e, i) => (o[e] = i + 1, o), {});
    console.log(COLUMNS_INDEXES); // { FIRST_NAME: 1, NICKNAME: 2, LAST_NAME: 3, ADDRESS: 4 }

    Sample script 3:

    const keys = ["FIRST_NAME", "NICKNAME", "LAST_NAME", "ADDRESS"];
    const COLUMNS_INDEXES = Object.fromEntries(keys.map((e, i) => [e, i + 1]));
    console.log(COLUMNS_INDEXES); // { FIRST_NAME: 1, NICKNAME: 2, LAST_NAME: 3, ADDRESS: 4 }