Skip to content

Instantly share code, notes, and snippets.

@chrislaughlin
Last active July 14, 2020 16:16
Show Gist options
  • Save chrislaughlin/618c28cf958dd7cd40435f99261c0872 to your computer and use it in GitHub Desktop.
Save chrislaughlin/618c28cf958dd7cd40435f99261c0872 to your computer and use it in GitHub Desktop.
const getKeyName = keyCode => {
switch (keyCode) {
case 37:
return "left";
case 38:
return "up";
case 39:
return "right";
case 40:
return "down";
case 65:
return "A";
case 66:
return "B";
}
};
const isKonamiCode = codes => {
return codes.join(" ") === "up up down down left right left right B A";
};
const useKonamiCode = () => {
const [keys, setKeys] = useState([]);
let timeout;
document.onkeydown = e => {
clearTimeout(timeout);
setKeys(currentKeys => [...currentKeys, getKeyName(e.keyCode)]);
timeout = setTimeout(() => {
setKeys([]);
}, 3000);
};
return {
isKonamiCode: isKonamiCode(keys),
keys
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment