Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fewer lines for switch statement?

I wonder if this … 

inputs.keydown(function (e) {
    switch (e.keyCode) {
        case 13:    //Enter
        case 16:    //Shift
        case 17:    //Ctrl
        case 18:    //Alt
        case 19:    //Pause/Break
        case 20:    //Caps Lock
        case 27:    //Escape
        case 35:    //End
        case 36:    //Home
        case 37:    //Left
        case 38:    //Up
        case 39:    //Right
        case 40:    //Down

        // Mac CMD Key
        case 91:    //Safari, Chrome
        case 93:    //Safari, Chrome
        case 224:   //Firefox
        break;
        default:
        $(this).addClass(fill);
        break;
    }
});

… is also possible with fewer lines? I know I could do an if-condition, but I wonder if I missed something like case 13 && 16 && …

Maybe some of you know a better practice to check all the cases and write fewer lines of code. I'm just wondering.

Thank you in advance!

like image 868
matt Avatar asked Dec 05 '22 16:12

matt


2 Answers

Just put the codes into an array, and then you can simply check if the value is in the array. Since you are using jQuery, you already have an inArray() method to do this.

var keycodes = [13, 16, 17, 18, 19]; //and so on

//if the keycode is not found in the array, the result will be -1
if ($.inArray(e.keyCode, keycodes) === -1) { 
    $(this).addClass(fill);
}
like image 200
kapa Avatar answered Dec 27 '22 04:12

kapa


You could create a "map" of the keys you don't want to handle - map lookups should be somewhere between O(1) and O(log n), depending on the implementation.

var specialKeys = {
    13: 1, // Enter
    16: 1, // Shift
    ...
    224: 1 // Cmd/FF
};

inputs.keydown(function (e) {
    if (e.keyCode in specialKeys) return;
    $(this).addClass(fill);
});

Alternatively as your "keys" are all integers you could fill an array where the indexes are the key code values.

EDIT removed the strings, as suggested by @bažmegakapa

like image 27
Alnitak Avatar answered Dec 27 '22 05:12

Alnitak