Double keypress in vanilla JavaScript

The algorithm is pretty straightforward once you wrap your mind around it:

  1. Bind to all keydown events
  2. When an event occurs, give it a unique slug, eg. ⌥-t corresponds to pressing CTRL and t
  3. Add to an array inside a map of all currently known presses
  4. Clear all known timeouts for a given slug
  5. Create a timeout to clear known presses after some threshold. In the example below I am using 300ms
  6. Measure length of array in map, if equal to 2, double keypress is found

And here's the code:

const map = {}
document.addEventListener('keydown', e => {
  const slug = `${ e.shiftKey ? '⇧-' : '' }${ e.ctrlKey ? '⌥-' : '' }${ e.metaKey ? '⌘-' : '' }${e.key}`
  map[slug] = map[slug] || []
  map[slug].forEach(clearTimeout)
  map[slug].push(setTimeout(() => delete map[slug], 300))
  if (map[slug].length === 2) {
    console.log(`Double keypress of ${slug}`)
  }
})