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:
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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With