0

Background: I'm thinking of writing a polyfill for KeyboardEvent.key and KeyboardEvent.code.

My proposal is to convert each combination of keyCode, charCode, shiftKey, etc. in the old standard to a key or code in the new standard.

It might look something like this:

function convertToNewKey(event) {
    var key;

    if (event.keyCode === 81 && event.charCode === 0 && shiftKey === false) {
        key = 'q'
    };    
    if (event.keyCode === 81 && event.charCode === 81 && shiftKey === true) {
        key = 'Q'
    };
    if (event.keyCode === 113 && event.charCode === 113) {
        key = 'q'
    };
    if (event.keyCode === 113 && event.charCode === 0) {
        key = 'F2'
    };
    // etc.

    return key;
}

This would require thousands of 'if' statements, and I'm not sure how fast it would run. Key events should be quick to respond to user input.

Is there another way -- such as nested hash maps or dictionaries -- that's easier to write, faster to execute, or both?

Edit: Seems hash maps are faster than 'if', although switch statements are faster than both, at least in some implementations. (Source: jsPerf) I may need to do some of my own speed-testing.

And one more thing: Tip of the hat to Jan Wolter for his research into keyboard events and his script that auto-prints their results.

jkdev
  • 11,360
  • 15
  • 54
  • 77
  • You will want to consider using `String.fromCharCode`. It'll deal with a whole alphabet in only one expression. – Bergi Jun 16 '15 at 03:15
  • Does it work the same way in all browsers? – jkdev Jun 16 '15 at 03:18
  • Yes, it does work the same in all browsers. Not saying that it'll just take `event.charCode` and be consistent across browsers, but you can use it to collapse an A to Z range into one expression, additional to the techniques explained in the duplicate. – Bergi Jun 16 '15 at 03:22
  • Which of them is fastest seems to depend largely on the engine. Use what is smallest/easiest to write. http://jsperf.com/if-vs-object-lookup-1/8 – Bergi Jun 16 '15 at 04:23

0 Answers0