TypeScript: Traffic light states

Model a traffic light with a literal union and step it through its cycle.

What to build

A program that prints the states of a traffic light.

Requirements

  • Declare type Light = "red" | "green" | "yellow" and next(light: Light): Light (red → green → yellow → red).
  • Print the starting light and then the light after each of the n steps, on one line separated by ->.
  • If the starting light is not one of the three, print unknown light X.

Input

Line 1: the starting light. Line 2: n.

Output

One line.

Constraints

0 ≤ n ≤ 20.

Example

Input:

red
4

Output:

red -> green -> yellow -> red -> green

Why it works

A literal union lists the only states a light can be in, so next() must cover each one, and text from the input has to be checked before TypeScript lets it be used as a Light.

Examples

Example 1 · Input
red
4
Expected output
red -> green -> yellow -> red -> green
Example 2 · Input
blue
2
Expected output
unknown light blue

Hints

Hint 1

type Light = "red" | "green" | "yellow", and a function next(light: Light): Light.

Hint 2

Check the input against the three values before treating it as a Light.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";

type Light = "red" | "green" | "yellow";

function next(light: Light): Light {
  if (light === "red") return "green";
  if (light === "green") return "yellow";
  return "red";
}

function isLight(text: string): text is Light {
  return text === "red" || text === "green" || text === "yellow";
}

const start = read();
const n = Number(read());
if (!isLight(start)) {
  console.log("unknown light " + start);
} else {
  const seen: Light[] = [start];
  let light: Light = start;
  for (let i = 0; i < n; i++) {
    light = next(light);
    seen.push(light);
  }
  console.log(seen.join(" -> "));
}

Lesson: Type aliases, unions and intersections →