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.