Computed switch cases

It would be nice to compute switch cases similarly to how computed property names work.

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

Ex:

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.

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;

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.

2 Likes

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

3 Likes