Traffic Lights- A Machine Coding Problem (Front-end)
I am back with another machine coding question frequently asked Senior Frontend Folks.
Expectations: Need to code it in React within 30–40 mins.
Problem Statement
Build a traffic light where the lights switch from green to yellow to red after predetermined intervals and loop indefinitely. Each light should be lit for the following durations:
- Red light: 4000ms
- Yellow light: 500ms
- Greenlight: 3000ms
You are free to exercise your creativity to style the appearance of the traffic light.
The UI can be something similar
The code-sandbox Link
I will be adding the CSS styles I used below (It is self-explanatory):
I implemented the UI using two components:
First is the App Component, and second is the TrafficLight Component, which displays the lights in the UI.
Step 1: In the App.js file we define a configuration config which is an object. The config specifies different colors and the duration for which the light should be lit.
Step 2:
Now, we need to render the TrafficLight Component in the App.js file. We pass the config as props to this component.
We will be discussing the TrafficLight component afterward.
Step 3:
Let’s create the TrafficLight component now.
Now, let’s break down the TrafficLight Component further.
Step 4:
The TrafficLight component renders the Lights through the Light Component, which takes the background color as a prop.
We also create a state currentColor to set the current color of the light. The initial color is set as green.
Step 5:
Now the next step is to implement the logic for lighting the divs for a specific duration and for a specific color.
For this, we need a useEffect with currentColor as a dependency. The duration of the color would be handled by setTimeout.
Step 6:
The last and most important step is to render the Lights by mapping through the config. We check if currentColor is the same as that of config while mapping, and then we set the backgroundColor from the config or else it is undefined.