Home > database >  How to DRY up this code (if else statement)
How to DRY up this code (if else statement)

Time:10-07

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';
        }
}

CodePudding user response:

Having an array of arrays for the rooms would mean you'd just have to add/subtract either the current X or Y coordinate. Something like:

const rooms = [
  [0, 2,0],
  [4, 1, 3],
  [0, 5, 0],
];

let horizIndex = 1;
let vertIndex = 1;
console.log(rooms[vertIndex][horizIndex]);

const changeRoom = (x, y) => {
  if (rooms[vertIndex   y][horizIndex   x]) {
    horizIndex = horizIndex   x;
    vertIndex = vertIndex   y;
    console.log('entered', rooms[vertIndex][horizIndex]);
  } else {
    console.log('Invalid room');
  }
};
const direction = 'south';
if (direction === 'south') {
  changeRoom(0, 1);
} else if (direction === 'north') {
  changeRoom(0, -1);
} else if (direction === 'east') {
  changeRoom(1, 0);
} else if (direction === 'west') {
  changeRoom(-1, 0);
}

CodePudding user response:

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;
  }
}

  • Related