1+ // @ts -check
2+
3+ export class ArgumentError extends Error { }
4+
5+ export class OverheatingError extends Error {
6+ constructor ( temperature ) {
7+ super ( `The temperature is ${ temperature } ! Overheating !` ) ;
8+ this . temperature = temperature ;
9+ }
10+ }
11+
12+ /**
13+ * Check if the humidity level is not too high.
14+ *
15+ * @param {number } humidityPercentage
16+ * @throws {Error }
17+ */
18+ export function checkHumidityLevel ( humidityPercentage ) {
19+ if ( humidityPercentage > 70 ) {
20+ throw new Error ( 'It/s getting hot in here' ) ;
21+ }
22+ }
23+
24+ /**
25+ * Check if the temperature is not too high.
26+ *
27+ * @param {number|null } temperature
28+ * @throws {ArgumentError|OverheatingError }
29+ */
30+ export function reportOverheating ( temperature ) {
31+ if ( temperature == null ) {
32+ throw new ArgumentError ;
33+ }
34+ if ( temperature > 500 ) {
35+ throw new OverheatingError ( temperature ) ;
36+ }
37+ }
38+
39+ /**
40+ * Triggers the needed action depending on the result of the machine check.
41+ *
42+ * @param {{
43+ * check: function,
44+ * alertDeadSensor: function,
45+ * alertOverheating: function,
46+ * shutdown: function
47+ * }} actions
48+ * @throws {ArgumentError|OverheatingError|Error }
49+ */
50+ export function monitorTheMachine ( actions ) {
51+ try {
52+ actions . check ( ) ;
53+ }
54+ catch ( error ) {
55+
56+ switch ( error . constructor ) {
57+
58+ case ArgumentError :
59+ actions . alertDeadSensor ( ) ;
60+ break ;
61+
62+ case OverheatingError : {
63+ if ( error . temperature < 600 ) {
64+ actions . alertOverheating ( ) ;
65+ break ;
66+ }
67+ if ( error . temperature > 600 ) {
68+ actions . shutdown ( ) ;
69+ break ;
70+ }
71+ }
72+ default :
73+ throw error ;
74+ }
75+ }
76+ }
0 commit comments