user5125647
user5125647

Reputation:

Replace switch statement with more concise logic

I have a chunk of code like

        switch (newDir)
        {
            case "left":
                {
                    this.dx = -1; this.dy = 0;
                    break;
                }
            case "up":
                {
                    this.dx = 0; this.dy = 1;
                    break;
                }
            case "right":
                {
                    this.dx = 1; this.dy = 0;
                    break;
                }
            case "down":
                {
                    this.dx = 0; this.dy = -1;
                    break;
                }
            default: // never happens
                break;
        }

which is meant to set the direction that an object in my game is moving. I think it's nicely readable, self-explanatory, but it's too bulky for my liking. I'm wondering if you guys know of a fancy way for me to consolidate it to

this.dx = ... ; 
this.dy = ... ; 

Maybe something that involves bitwise operators or maps or something.

Upvotes: 1

Views: 244

Answers (2)

metalim
metalim

Reputation: 1613

Just for the sake of it...

dir_map = {right:0,up:1,left:2,down:3}
dirs = [[1,0],[0,1],[-1,0],[0,-1]]

dir = dir_map[newDir] // and keep it as number from now on. Never get back to string.
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]

Even if neutral direction is required:

if (dir != null) {
    this.dx += dirs[dir][0]
    this.dy += dirs[dir][1]
}

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30587

Use an object as a map

var directions = {
  'left': {
    dx : -1, dy : 0
  },
  'right': {
    dx : 1, dy : 0
  },
  'up': {
    dx : 0, dy : 1
  },
  'down': {
    dx : 0, dy : -1
  }
};

this.dx = directions[newDir].dx;
this.dy = directions[newDir].dy;

Upvotes: 4

Related Questions