What you're building
The entire 2048 game reduces to one operation: sliding a row left. Get that right and you can apply it four ways (left, right, up, down) to drive the full board.
You will implement:
slideLeft(row)โ takes a 4-element array of numbers (zeros = empty), returns the merged row slid left.applyMove(board, direction)โ takes a 4ร4 board (array of 4 rows) and a direction ("left","right","up","down"), returns the new board after one move.
Requirements
slideLeft rules (canonical 2048 behaviour):
- Compact all non-zero tiles to the left, leaving zeros on the right.
- Merge adjacent equal tiles (left-to-right, first match wins); merged tile doubles.
- A tile produced by merging cannot merge again in the same move.
- Fill remaining spots with zeros so the row stays 4 elements long.
applyMove:
"left": slideLeft each row."right": reverse, slideLeft, reverse each row."up": transpose, apply left, transpose back."down": transpose, apply right, transpose back.
Stretch goals
- Add a
scoreaccumulator that sums merged tile values. - Detect a "game over" state (no valid moves remain).
What this proves
Row/column transformations, immutable data manipulation, and translating a visual game mechanic into clean logic โ all classic array-manipulation interview fodder.
โก 40 XP
solution.jsRuns in your browser
Loading editorโฆ
Tests4 to pass
slideLeft compacts and merges
slideLeft does not double-merge
applyMove left slides all rows
applyMove right slides all rows
Run your code to check these.