Happylab Logo
Published on

Day12: Key Sequence Detection

Authors
js30

Project Introduction: Display surprise images on the page after entering a secret code.

Project Page: https://iris1114.github.io/javascript30/12_Key-Sequence-Detection/

Code

const pressed = []
const secretCode = 'ok'

window.addEventListener('keyup', (e) => {
  // Add pressed keyboard elements to array
  pressed.push(e.key)

  // Keep pressed array length equal to secret code length by replacing first element when exceeded
  pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length)
  // Check if input array content matches secret code
  if (pressed.join('').includes(secretCode)) {
    cornify_add()
  }
})

Additional Notes

splice()

splice(start, deleteCount, item1, item2, ...) can delete or add array elements.

start: Index at which to start changing the array delete: Integer indicating the number of elements to remove item1, item2, ...: Elements to add to the array starting from start

const months = ['Jan', 'March', 'April', 'June']
months.splice(1, 0, 'Feb') //["Jan", "Feb", "March", "April", "June"]

const arr = [1, 2, 3]
arr.splice(0, 1) //[2,3]

join()

arr.join([separator]) joins all elements of an array into a string and returns this string.

separator: If omitted, array elements are separated with a comma (,). If separator is an empty string, elements are joined without any characters between them.

const elements = ['Fire', 'Air', 'Water']

console.log(elements.join())
// expected output: "Fire,Air,Water"

console.log(elements.join(''))
// expected output: "FireAirWater"

console.log(elements.join('-'))
// expected output: "Fire-Air-Water"

includes()

arr.includes(searchElement[, fromIndex]) determines whether an array includes a certain value, returning true or false.

const pets = ['cat', 'dog', 'bat']

console.log(pets.includes('cat'))
// expected output: true

console.log(pets.includes('at'))
// expected output: false

References

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice