Skip to content

Instantly share code, notes, and snippets.

@ptcc
Last active May 12, 2023 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptcc/937d9d402df2f2daca7a1005f394a7c6 to your computer and use it in GitHub Desktop.
Save ptcc/937d9d402df2f2daca7a1005f394a7c6 to your computer and use it in GitHub Desktop.
function makeHotKeys() {
let commands = {};
const keyMap = {};
let largestKeyValue = 0;
let bitValues = [];
function bitValue(bit) {
bitValues[bit] = bitValues[bit] || 2n ** BigInt(bit);
return bitValues[bit];
}
function keyValue(key) {
if (!keyMap.hasOwnProperty(key)) {
keyMap[key] = largestKeyValue++;
}
return bitValue(keyMap[key]);
}
function getKeysHash(keys) {
return keys.reduce((val, key) => val + keyValue(key), 0n);
}
function getCommand(keys) {
const hash = getKeysHash(keys);
return commands[hash];
}
function setCommand(keys, commandName) {
const hash = getKeysHash(keys);
commands[hash] = commandName;
}
return { setCommand, getCommand };
}
const { setCommand, getCommand } = makeHotKeys();
function preprocess(commandList) {
commandList.forEach((str) => {
const parts = str.split(' ');
commandName = parts.pop();
setCommand(parts, commandName);
});
}
function findCommand(pressedKeysStr) {
const pressedKeys = pressedKeysStr.split(' ');
return getCommand(pressedKeys) || '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment