Skip to content

Commit

Permalink
Optimize _keyArgToScratchKey
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
GarboMuffin committed May 31, 2024
1 parent 16415ba commit dff3c2f
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/io/keyboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ const KEY_NAME = {
};

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

class Keyboard {
constructor (runtime) {
Expand Down Expand Up @@ -121,7 +121,9 @@ class Keyboard {
keyArg = Cast.toString(keyArg);

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

Expand Down

0 comments on commit dff3c2f

Please sign in to comment.