Workshop › 2048 › Step 16 of 26
Up and down work on columns: read a column from top to bottom as if it were a row, slide it "left" (towards the top), and write it back. Down is the same, reversed. One tested function, reused four ways.
```js
// Every direction is "slide left" on a row or a column, possibly reversed.
function move(direction) {
const before = JSON.stringify(board)
const horizontal = direction === 'left' || direction === 'right'
const reversed = direction === 'right' || direction === 'down'
for (let i = 0; i < SIZE; i++) {
const line = horizontal ? [...board[i]] : board.map((row) => row[i])
if (horizontal) board[i] = row
else row.forEach((value, r) => (board[r][i] = value))
const directions = { ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down' }
```horizontal is true for left and right; for up and down, i is a column.board.map((row) => row[i]) makes a new array of the ith item of every row: the column, top to bottom.forEach((value, r) => ...) writes the slid column back, one row at a time.reversed includes 'down'.function move, write the comment.reversed line with the horizontal and reversed lines shown.line line, and replace board[i] = row with the two lines.ArrowUp and ArrowDown to the table.Skills: Arrays and objects, Functions
← Right is left, reversed Score →