Skip to content

Instantly share code, notes, and snippets.

@wiledal
Created August 23, 2021 20:10
Show Gist options
  • Save wiledal/d9b7e2c22427fb8d45f44d41ba90133e to your computer and use it in GitHub Desktop.
Save wiledal/d9b7e2c22427fb8d45f44d41ba90133e to your computer and use it in GitHub Desktop.
Simple konami code hook
import { useEffect, useRef } from "react";
const UP = "ArrowUp";
const DOWN = "ArrowDown";
const LEFT = "ArrowLeft";
const RIGHT = "ArrowRight";
const B = "b";
const A = "a";
export const KONAMI_CODE = [UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A];
const isBrowser = typeof window !== "undefined";
export const useKonami = (callback?) => {
const index = useRef(0);
useEffect(() => {
const handleKeyDown = (event) => {
let currKey = KONAMI_CODE[index.current];
if (event.key == currKey) {
index.current++;
} else {
index.current = 0;
}
if (index.current === KONAMI_CODE.length) {
index.current = 0;
console.log("k o n a m i");
if (callback) callback();
}
};
if (isBrowser) window.addEventListener("keydown", handleKeyDown);
return () => {
if (isBrowser) window.removeEventListener("keydown", handleKeyDown);
};
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment