Skip to content

Commit dff3c2f

Browse files
committed
Optimize _keyArgToScratchKey
The special key name list is now a set instead of an array. In the most common case of a simple letter, a search is skipped entirely. Test coverage already exists.
1 parent 16415ba commit dff3c2f

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/io/keyboard.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ const KEY_NAME = {
2727
};
2828

2929
/**
30-
* An array of the names of scratch keys.
31-
* @type {Array<string>}
30+
* A set of the names of Scratch keys.
31+
* @type {Set<string>}
3232
*/
33-
const KEY_NAME_LIST = Object.keys(KEY_NAME).map(name => KEY_NAME[name]);
33+
const KEY_NAME_SET = new Set(Object.values(KEY_NAME));
3434

3535
class Keyboard {
3636
constructor (runtime) {
@@ -121,7 +121,9 @@ class Keyboard {
121121
keyArg = Cast.toString(keyArg);
122122

123123
// If the arg matches a special key name, return it.
124-
if (KEY_NAME_LIST.includes(keyArg)) {
124+
// No special keys have a name that is only 1 character long, so we can avoid the lookup
125+
// entirely in the most common case.
126+
if (keyArg.length > 1 && KEY_NAME_SET.has(keyArg)) {
125127
return keyArg;
126128
}
127129

0 commit comments

Comments
 (0)