TypeScript: A temperature class with getters and setters

Keep one temperature and read or change it in Celsius, Fahrenheit or kelvin through getters and setters.

What to build

A program that sets and shows a temperature in three scales.

Requirements

  • Write class Temperature that stores the temperature in a private field and has getters and setters celsius, fahrenheit and kelvin.
  • set c V, set f V and set k V set the temperature; a value below absolute zero (0 K) prints below absolute zero and changes nothing.
  • show prints C °C = F °F = K K, each to one decimal place. The temperature starts at 0 °C.

Input

Line 1: n. Then n commands.

Output

One line per show and per refused value.

Constraints

1 ≤ n ≤ 50; |V| ≤ 10000.

Example

Input:

4
show
set c 100
show
set k -1

Output:

0.0 °C = 32.0 °F = 273.1 K
100.0 °C = 212.0 °F = 373.1 K
below absolute zero

Why it works

Storing a single value and converting in the accessors means the three scales can never disagree, and the check against absolute zero lives in one place that every setter goes through.

Examples

Example 1 · Input
4
show
set c 100
show
set k -1
Expected output
0.0 °C = 32.0 °F = 273.1 K
100.0 °C = 212.0 °F = 373.1 K
below absolute zero
Example 2 · Input
3
set f -40
show
set c -300
Expected output
-40.0 °C = -40.0 °F = 233.1 K
below absolute zero

Hints

Hint 1

Store one value, in kelvin, in a private field; the getters and setters convert.

Hint 2

A setter can refuse a value; here, print a message and keep the old one.

Solution

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

class Temperature {
  private k = 273.15;

  private store(kelvin: number): void {
    if (kelvin < 0) console.log("below absolute zero");
    else this.k = kelvin;
  }

  get kelvin(): number {
    return this.k;
  }
  set kelvin(v: number) {
    this.store(v);
  }

  get celsius(): number {
    return this.k - 273.15;
  }
  set celsius(v: number) {
    this.store(v + 273.15);
  }

  get fahrenheit(): number {
    return (this.celsius * 9) / 5 + 32;
  }
  set fahrenheit(v: number) {
    this.store(((v - 32) * 5) / 9 + 273.15);
  }
}

const t = new Temperature();
const n = Number(read());
for (let i = 0; i < n; i++) {
  const [command, scale, text] = read().split(" ");
  if (command === "show") {
    console.log(t.celsius.toFixed(1) + " °C = " + t.fahrenheit.toFixed(1) + " °F = " + t.kelvin.toFixed(1) + " K");
  } else if (scale === "c") t.celsius = Number(text);
  else if (scale === "f") t.fahrenheit = Number(text);
  else t.kelvin = Number(text);
}

Lesson: Classes in TypeScript →