JavaScript 30 – Day 12: Key Sequence Detection

Welcome to my recap of Day 12 of the free JavaScript 30 online video course by Wes Bos. In case you really have not yet heard of the course, quickly head over to it and get started right away! 🙂

Please refer to the JavaScript 30 archive for all recap posts.

Objective

On Day 12, the task is to detect a given key sequence in the user input, and react to that.

The provided starter files consist of a single, almost empty HTML file.

I stopped the video right after the objective has been made clear, and started implementing it on my own.

Conception

The conception is pretty much clear, right? Here it is:

  • store user input;
  • if it matches a given key sequence, … do something.

Implementation

Following the conception, we first have to define the key sequence that should be detected; I chose the Konami Code. 🙂

const keySequence = [
    'ArrowUp',
    'ArrowUp',
    'ArrowDown',
    'ArrowDown',
    'ArrowLeft',
    'ArrowRight',
    'ArrowLeft',
    'ArrowRight',
    'b',
    'a',
];

We then start with an empty array of equal size to keep track of the user input:

let userInput = new Array( keySequence.length );

Finally, we listen to the keydown event, and update the user input storage by shifting all items, and appending the current key. This is done by combining slicing, spreading, and declaring the user input array.

If the user input matches the Konami Code, an alert gets displayed.

window.addEventListener( 'keydown', ( { key } ) => {
    userInput = [ ...userInput.slice( 1 ), key ];

    if ( keySequence.every( ( v, k ) => v === userInput[ k ] ) ) {
        alert( 'Yatta!' );
    }
} );

Unfortunately, checking if two arrays have the same values still cannot be done (more) easily. There really should be something like Array.prototype.equals( otherArray ), right?!

Refinement

Nope, watching the video didn’t make me change a thing in my code. In fact, I find Wes’s solution a little … overcomplicated.

If the user input storage should be a const, you can easily achieve this by using .slice() and .push(). No need for the (complicated) .splice().

Live Demo

Want to see this in action? Well, here is a live demo. Now, you just have to input the Konami Code. 🙂

Retrospection

This was pretty cool. I didn’t take away much, though.

And You?

JavaScript 30 is free! So, unless you already did this on your own, what’s your reason not to? 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *