# Computed switch cases

**URL:** <https://es.discourse.group/t/computed-switch-cases/1642>\
**Category:** 💡 Ideas\
**Created:** [March 19, 2023, 9:34pm UTC](https://es.discourse.group/t/computed-switch-cases/1642 "2023-03-19T21:34:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Cooldogyum](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/cooldogyum/32/1679_2.png) [@Cooldogyum](https://es.discourse.group/u/Cooldogyum)\
**Post date:** [March 19, 2023, 9:34pm UTC](https://es.discourse.group/t/computed-switch-cases/1642/1 "2023-03-19T21:34:49Z")

</div>

It would be nice to compute switch cases similarly to how [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names:~:text=expression%20in%20brackets) work.

For example, recently, I wanted to use a switch statement to compare against a list of possible values.

Ex:

```js
const TILE_TYPES = {
    WALL: 0,
    WATER: 1,
    MUD: 2,
};

switch (tileType) {
    case [TILE_TYPES.WALL]: {
        ...
    }
    case [TILE_TYPES.WATER]: {
        ...
    }
    case [TILE_TYPES.MUD]: {
        ...
    }
    default: {
        return false;
    }
}

```

Unfortunately, I believe this is unsupported and would require statically typing the values, so I ended up using a helper function that wraps an object, but that comes with its issues.

```js
const TILE_TYPE_CASES = {
    [TILE_TYPES.WALL]: () => {
        ...
    },
    [TILE_TYPES.WATER]: () => {
        ...
    },
    [TILE_TYPES.MUD]: () => {
        ...
    },
    default: () => {
        return true;
    },
};
const tileTypeSwitch = switchFunction(TILE_TYPE_CASES);
const shouldReturn = tileTypeSwitch(tileType);
if (shouldReturn) return;

```

---

<div class="post-metadata">

**Author:** ![ljharb](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/ljharb/32/8_2.png) [@ljharb](https://es.discourse.group/u/ljharb)\
**Post date:** [March 19, 2023, 9:53pm UTC](https://es.discourse.group/t/computed-switch-cases/1642/2 "2023-03-19T21:53:39Z")

</div>

Why would `case TILE_TYPES.WALL:` etc not Just Work as-is? `case` accept any expression to `===` to the thing being switched on, not just static things.

---

<div class="post-metadata">

**Author:** ![Cooldogyum](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/cooldogyum/32/1679_2.png) [@Cooldogyum](https://es.discourse.group/u/Cooldogyum)\
**Post date:** [March 20, 2023, 3:15am UTC](https://es.discourse.group/t/computed-switch-cases/1642/3 "2023-03-20T03:15:39Z")

</div>

Ah, it seems I must have just been a goofball when trying to do so.
