用更简洁的逻辑替换switch语句

时间:2015-07-28 18:02:12

标签: javascript algorithm optimization

我有一大堆代码,比如

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

用于设置游戏中的对象移动的方向。我觉得它很可读,不言自明,但对我来说太笨重了。我想知道你们是否知道一种奇特的方式让我把它整合到

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

可能是涉及按位运算符或映射等的东西。

2 个答案:

答案 0 :(得分:4)

将对象用作地图

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;

答案 1 :(得分:0)

只是为了它......

<android.support.design.widget.TextInputLayout
    android:id="@+id/til_email"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <AutoCompleteTextView
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/prompt_email"
        android:inputType="number"
        android:imeOptions="actionNext"
        android:maxLines="1"
        android:singleLine="true" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/til_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/prompt_password"
        android:imeActionId="6"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionUnspecified"
        android:inputType="numberPassword"
        android:maxLines="1"
        android:singleLine="true" />
</android.support.design.widget.TextInputLayout>

即使需要中立方向:

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]