Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Traffic Light State Machine

Object-Oriented Programmingeasy

Course · Section 14: Object-Oriented Programming (OOP) With JavaScript · Lecture 226: ES6 Classes

Model a traffic light cycling red, green, yellow, then back to red. Implement `TrafficLight` (starts red): - `next()` advances to and returns the next state. - `current()` returns the current state.

Examples

Input: current(), next(), next(), next(), next()
Output: ['red', 'green', 'yellow', 'red', 'green']
Starting red, the light cycles green, yellow, red, green.

Sample tests

Input: cycle through states
Output: ["red","green","yellow","red","green"]
Input: one step
Output: "green"

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Hardcoding an if-chain is fine but a map is cleaner and avoids missed cases.
Approach & explanation (try first)

A state-transition table advances the light deterministically through its cycle.

Loading...
⌘/Ctrl + Enter

Run your code to see results.