Skip to content

belfz/elevator-state-machine

Repository files navigation

Elevator State Machine

I always wanted to reverse-engineer the logic behind an elevator — how it decides which floor to visit next, when to reverse direction, and how it juggles multiple requests without wasting trips. This project is the result: a 7-floor elevator simulation built from scratch as a pure state machine, with an interactive UI to watch it "think".

Elevator Simulator UI

How it works

The elevator uses the SCAN (elevator) algorithm — the same scheduling strategy used in real elevators (and disk I/O). The rule is simple: keep moving in the current direction as long as there are requests ahead, then reverse. This avoids unnecessary back-and-forth and serves requests efficiently.

The simulation runs on a tick-based clock (10 Hz). Each tick, the state machine decides what to do based on the current phase:

  • Idle — no requests? Wait. Request at the current floor? Open doors. Otherwise, pick a direction and start moving.
  • Moving — advance one tick. Landed on a floor with a matching request? Stop and open doors. Otherwise, keep going.
  • Door open — count down a 3-second timer, then return to idle.

All position tracking uses integer ticks rather than floating-point meters, which eliminates precision issues entirely.

Architecture

The project has two cleanly separated layers:

Pure state machine (src/lib/elevator/) — A transition(state, event) -> state pure function with fully immutable state. All elevator logic — SCAN scheduling, request tracking, phase transitions — lives there, testable in isolation (see related unit tests).

Svelte 5 UI (src/components/) — A thin reactive wrapper (Simulation class) drives the state machine via setInterval and exposes state through Svelte 5 runes ($state). Components read this reactive state to render the shaft with CSS-animated cabin movement, sliding doors, call buttons with active highlights, and a debug inspector showing raw state.

The state machine knows nothing about the UI. The UI knows nothing about elevator logic. The Simulation class is the only bridge between them.

Setup

npm install
npm run dev       # start dev server at http://localhost:5173
npm run test      # run unit tests
npm run check     # typecheck
npm run lint      # lint
npm run format    # format with prettier

Tech stack

TypeScript, Svelte 5, Vite 7, Vitest, vanilla CSS

About

Pure functional elevator state machine with SCAN scheduling algorithm, visualized with Svelte 5

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors