Search code examples
javascriptif-statementdry

How to DRY up this code (if else statement)


What is the best way to make this code more dry? I was thinking of nesting the if-statements where currentRoom.id is the same, or just condense it by adding an || part inside the conditional. But I am not sure if those solutions make the code any neater.

What is the most reasonable and concise style for this kind of thing?

if(direction === 'east' && player.currentRoom.id === 1) {
          roomNum = '3';
        } else if (direction ==='east' && player.currentRoom.id === 4) {
          roomNum = '1';
        } else if (direction === 'west' && player.currentRoom.id === 1) {
          roomNum = '4';
        } else if (direction === 'west' && player.currentRoom.id === 3) {
          roomNum = '1';
        } else if (direction === 'north' && player.currentRoom.id === 5) {
          roomNum = '1';
        } else if (direction === 'north' && player.currentRoom.id === 1) {
          roomNum = '2';
        } else if (direction === 'south' && player.currentRoom.id === 1) {
          roomNum = '5';
        } else if (direction === 'south' && player.currentRoom.id === 2) {
          roomNum = '1';
        }
}

Solution

  • Without any other program refactoring, you can compact the repeated syntax in your example by looping over an array of tuples consisting of the variable data in each clause, breaking after the first potential match:

    for (const [dir, id, num] of [
      ['east',  1, '3'],
      ['east',  4, '1'],
      ['west',  1, '4'],
      ['west',  3, '1'],
      ['north', 5, '1'],
      ['north', 1, '2'],
      ['south', 1, '5'],
      ['south', 2, '1'],
    ]) {
      if (direction === dir && player.currentRoom.id === id) {
        roomNum = num;
        break;
      }
    }