← Decorator lesson
Lab

Decorator

Sign in to run your code

Read the brief and the starter here. With a free account you can edit it, run the sample, step through it and check your work, and your progress is kept.

// A temperature source. read() throws when the probe is offline.
interface Sensor {
  read(): number;
  unit(): string;
}

// What each reader gets from setup.
type Readers = { dashboard: Sensor; alerts: Sensor };

// The dashboard shows the current temperature.
function dashboardLine(sensor: Sensor): string {
  try {
    // The probe reads low; corrected here by hand last month.
    const reading = sensor.read() + 0.8;
    return `bench 3: ${reading.toFixed(1)}°${sensor.unit()}`;
  } catch {
    return 'bench 3: probe offline';
  }
}

// The frost alert pages the grower below 2.0 °C.
function frostCheck(sensor: Sensor): string {
  try {
    const reading = sensor.read();
    const shown = `${reading.toFixed(1)}°${sensor.unit()}`;
    return reading < 2 ? `frost alert: ${shown}` : `ok: ${shown}`;
  } catch {
    return 'frost check: probe offline';
  }
}

// Setup builds what each reader gets. The checker calls it with the probe
// and the bench's calibration: how far the probe reads low, in °C.
function benchSensors(probe: Sensor, calibration: number): Readers {
  return { dashboard: probe, alerts: probe };
}

// Checker plumbing, you don't need to edit this: the bench probe. Each read
// takes the next scripted reading; null means the probe is offline.
function benchProbe(readings: (number | null)[]): Sensor {
  const script = [...readings];
  return {
    read() {
      const reading = script.shift();
      if (reading == null) throw new Error('probe offline'); // none left, or offline
      return reading;
    },
    unit: () => 'C',
  };
}