JS - Alphanumeric Keypad Keypad Dial Code 2 - 9

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

So, for example, by pressing "A" on the keyboard, highlight "2" in the user interface:

dialing user interface

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

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

Q: Is there a way to do this on the same line, so will PQRS and WXYZ match the solution?

+7
javascript math web widget keydown
source share
2 answers

If you really need it, this might work:

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

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

The obvious solution that you discussed is much better, because it is read, configured and configured equally quickly:

  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; } 
+5
source share

[Map] - the obvious solution, I am considering a mathematical solution

If you are looking for an analytic expression, you can fit, for example. quadratic or exponential function to a given mapping of key codes into numbers: keycode fit

 // Exponential fit: Math.floor(33.2 - 65.5 * Math.exp(-0.0115 * KeyCode)); 

Alternatively, you can encode "anomalies" occurring on code code> 82 and keycode> 89 using the comparison operator.

 // Comparison: Math.floor((KeyCode - 65 - (KeyCode > 82) - (KeyCode > 89)) / 3 + 2); 

Exponential matching has the advantage that a keyword term appears only once, and a later expression is more readable.

Implementation / test example:

 // Quadratic fit: var sqr = (k) => -0.0018 * k * k + 0.59 * k - 28.6 | 0; // Exponential fit: var exp = (k) => 33.2 - 65.5 * Math.exp(-0.0115 * k) | 0; // Comparison: var cmp = (k) => (k - 65 - (k > 82) - (k > 89)) / 3 + 2 | 0; for (var k = 65; k <= 90; ++k) { console.log(String.fromCharCode(k), sqr(k), exp(k), cmp(k)); } 
+3
source share

All Articles