Skip to content

Instantly share code, notes, and snippets.

@gabrielfreirebraz
Last active January 12, 2024 20:45
Show Gist options
  • Save gabrielfreirebraz/947def7fe08d1663d881584a81378d29 to your computer and use it in GitHub Desktop.
Save gabrielfreirebraz/947def7fe08d1663d881584a81378d29 to your computer and use it in GitHub Desktop.
Konami code for typescript
export const Konami = (() => {
// up, up, down, down, left, right, left, right, b, a, enter
const SEQUENCE: Array<number> = [
38,
38,
40,
40,
37,
39,
37,
39,
66,
65,
13,
];
let head: number = 0;
let isActive: boolean = false;
let callback: Function | undefined;
const start = (cb: Function): void => {
if (isActive) {
return;
}
window.addEventListener("keydown", onKeyDown);
callback = cb;
isActive = true;
};
const stop = (): void => {
if (!isActive) {
return;
}
isActive = false;
window.removeEventListener("keydown", onKeyDown);
};
const onKeyDown = (event: any) => {
if (event.keyCode === SEQUENCE[head]) {
head++;
if (head === SEQUENCE.length) {
if (callback instanceof Function) {
callback();
}
head = 0;
}
} else {
head = 0;
}
};
return {
start,
stop,
};
})();
// how to call it in the application
export const App = () => {
const [konamiActive, setKonamiActive] = useState(false);
useEffect(() => {
console.log(konamiActive)
Konami.start(() => {
setKonamiActive((currValue) => !currValue);
});
},[konamiActive])
return (
<>
// make <KonamiBackground/> as one component for screen show of konamicode
{konamiActive && <KonamiBackground/>}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment