ghoullier
1/2/2015 - 11:21 AM

Konami code detection

Konami code detection

;(function main(exports) {
  var KONAMI_KEYS = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]
  var KONAMI_KEYS_LENGTH = KONAMI_KEYS.length

  var callbacks = []
  var index = 0

  document
    .documentElement
    .addEventListener('keydown', detect, true)


  exports.registerCallback = registerCallback

  function registerCallback(callback) {
    callbacks.push(callback)
  }

  function invoke(callback) {
    callback()
  }

  function detect(event) {
    if (event.keyCode === KONAMI_KEYS[index++]) {
      if (KONAMI_KEYS_LENGTH === index) {
        index = 0
        callbacks.forEach(invoke)
      }
    } else {
      index = 0
    }
  }

}(this.konami = {}))