Created
October 15, 2024 19:55
-
-
Save cyyynthia/8009319c5dd381e16031604f9d820cae to your computer and use it in GitHub Desktop.
Very small (376B minified) implementation of Konami code in TypeScript (0BSD licensed)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* BSD Zero Clause License | |
* Copyright (c) Cynthia Rey | |
* SPDX-License-Identifier: 0BSD | |
* | |
* Permission to use, copy, modify, and/or distribute this software for any | |
* purpose with or without fee is hereby granted. | |
* | |
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | |
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | |
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | |
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | |
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | |
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | |
* PERFORMANCE OF THIS SOFTWARE. | |
*/ | |
// Hack to not be annoyed by number vs NodeJS.Timeout shenanigans | |
type Timeout = ReturnType<typeof setTimeout> | |
let keys: string[] = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'B', 'A'] | |
let current: number = 0 | |
let timeout: Timeout | null = null | |
window.addEventListener('keydown', (e) => { | |
if (timeout) { | |
clearTimeout(timeout) | |
timeout = null | |
} | |
// If modifier is pressed, ignore | |
if (e.ctrlKey || e.shiftKey || e.altKey || e.metaKey) { | |
current = 0 | |
return | |
} | |
// Check the sequence | |
let k = e.key.length > 1 ? e.key : e.key.toUpperCase() | |
if (keys[current] === k) { | |
current++ | |
} | |
// We got the code! | |
if (keys.length === current) { | |
current = 0 | |
onKonamiCode() | |
} else { | |
// Consider the attempt abandoned if no key is pressed within a second | |
timeout = setTimeout(() => { | |
current = 0 | |
timeout = null | |
}, 1e3) | |
} | |
}) | |
function onKonamiCode () { | |
console.log('nerd') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment