1

I have the following function:

gameActions(e: KeyboardEvent) {
        if (e.keyCode === 27 || e.keyCode === 9 || (e.keyCode === 9 && e.shiftKey)) { 
            this.LaunchInventory();
        }
        else if (e.keyCode === 13) { //Enter
            this.Shoot();
        }
        else if (e.keyCode === 40) { //Down
            this.Crouch();
        }
        else if (e.keyCode === 38) { //Up
            this.Jump();
        }
    }

How can I implement this code using switch case? I am just unable to figure out how to pass the conditional statement e.shiftKey && e.keyCode to the case statement.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
zelda
  • 753
  • 2
  • 8
  • 19
  • 1
    This doesn’t look like JavaScript. Anyway, show us what you’ve tried. – Sebastian Simon Mar 01 '17 at 20:49
  • The first `if` statement is not dependent on `e.shiftKey`. `if (e.keyCode === 27 || e.keyCode === 9)` is sufficient. – Peter Mar 01 '17 at 20:51
  • Just a tip: Your final conditional for LaunchInventory() is redundant. If `(e.keyCode === 9 && e.shiftKey)` is true, then just `e.keyCode === 9` is also true. – AmericanUmlaut Mar 01 '17 at 20:52

1 Answers1

8

The e.keyCode === 9 && e.shiftKey condition is completely redundant, as checking for e.keyCode === 9 would suffice to enter the same condition. You could just drop it, which would make using a switch-case quite straight forward:

gameActions(e: KeyboardEvent) {
    switch(e.keycode) {
        case 27:
        case 9:
            this.LaunchInventory();
            break;
        case 13:
            this.Shoot();
            break;
        case 40:
            this.Crouch();
            break;
        case 38:
            this.Jump();
            break;
    }
Mureinik
  • 297,002
  • 52
  • 306
  • 350