Workshop › Snake › Step 18 of 28
Four almost identical if lines become one lookup table: key name → direction. Same behavior, easier to change.
```js
const turns = {
ArrowUp: { x: 0, y: -1 },
ArrowDown: { x: 0, y: 1 },
ArrowLeft: { x: -1, y: 0 },
ArrowRight: { x: 1, y: 0 },
}
document.addEventListener('keydown', (event) => {
const turn = turns[event.key]
if (!turn) return
dir = turn
})
```turns is an object used as a table: each key name leads to a direction.turns[event.key] looks the pressed key up; for other keys there is no entry, so it is undefined.if (!turn) return stops early when the key is not an arrow.Replace the whole listener with turns and the shorter listener.
Skills: Refactoring
← Never put food on the snake No U-turns →