Skip to content

Instantly share code, notes, and snippets.

@ssajous
Last active December 16, 2017 06:11
Show Gist options
  • Save ssajous/88ff50ab820f59f58b5ec807541675a9 to your computer and use it in GitHub Desktop.
Save ssajous/88ff50ab820f59f58b5ec807541675a9 to your computer and use it in GitHub Desktop.
ES6 module to handle the Konami code input in a browser.
const _code = "38384040373937396665";
export default class CheatCode {
code = '';
delay = 1500;
callbacks = [];
timeout = null;
constructor() {
this.handler = this.handler.bind(this);
this.dispatch = this.dispatch.bind(this);
document.addEventListener("keydown", this.handler, false);
}
handler(e) {
try {
clearTimeout(this.timeout);
} catch (error) { }
this.code = String(this.code + e.keyCode);
if (this.code === _code) {
this.dispatch("cheat code");
}
this.timeout = setTimeout(() => {
clearTimeout(this.timeout);
this.code = '';
}, this.delay);
}
listen(callback) {
if (typeof callback === "function") {
this.callbacks.push(callback);
}
return this;
}
dispatch() {
for (let i = this.callbacks.length; i--;) {
this.callbacks[i]();
}
}
}
@ssajous
Copy link
Author

ssajous commented Dec 14, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment