Advertisement
Notimecelduv

Factory Sensors

Dec 19th, 2021 (edited)
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://exercism.org/tracks/javascript/exercises/factory-sensors
  2.  
  3. function checkHumidityLevel(percentage) {
  4.   if (percentage > 70)
  5.     throw new Error(`Humidity level is too high.`);
  6. }
  7.  
  8. class ArgumentError extends Error {
  9.   constructor(message) {
  10.     super(message);
  11.   }
  12. }
  13.  
  14. class OverheatingError extends Error {
  15.   temperature;
  16.  
  17.   constructor(message, temperature) {
  18.     super(message);
  19.     this.temperature = temperature;
  20.   }
  21. }
  22.  
  23. function reportOverheating(temperature) {
  24.   if (temperature === null)
  25.     throw new ArgumentError(`Sensor is broken.`);
  26.   if (temperature > 500)
  27.     throw new OverheatingError(`Temperature is too high.`, temperature);
  28. }
  29.  
  30. function monitorTheMachine({ check, alertDeadSensor, alertOverheating, shutdown }) {
  31.   try {
  32.     check();
  33.     return;
  34.   } catch (error) {
  35.     if (error instanceof ArgumentError)
  36.       return alertDeadSensor();
  37.     if (error instanceof OverheatingError)
  38.       return (error.temperature < 600)
  39.         ? alertOverheating()
  40.         : shutdown();
  41.     throw error;
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement