Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Map alphanumeric keyboard keyCode to a dial pad number 2 - 9

I'm trying to create a dialer widget, catch "keydown" event and highlight the corresponding dialer number.

So, for example clicking "A" on the keyboard, would highlight "2" on the UI:

dialer HTML UI

I've managed to map the first 5 digits (2-6). Since they contain 3 letters each, I was able to map the keyCode like so:

Math.floor(((KeyCode - 65) / 3) + 2).

Q: Is there a way to do it in one line, so PQRS and WXYZ would fit the solution?

like image 839
Shlomi Schwartz Avatar asked Jul 04 '16 08:07

Shlomi Schwartz


1 Answers

If you really need it, that might work:

    Math.min(9, Math.floor(((KeyCode - (KeyCode < 83 ? 65 : 66)) / 3) + 2))

but you also have to make sure that KeyCode actually is a letter.

The obvious solution you discussed is way better, because it's readable, configurable, and peforms equally fast:

    function toDialNumber(KeyCode) {
      var keyMap = {1:"", 2:"ABC", 3:"DEF", 4:"GHI", 5:"JKL", 6:"MNO", 7:"PQRS", 8:"TUV", 9:"WXYZ"};
      var letter = String.fromCharCode(KeyCode);
      for(key in keyMap) if(keyMap[key].indexOf(letter)>=0) return key;
      return false;
    }
like image 109
dercz Avatar answered Oct 23 '22 12:10

dercz