-
Notifications
You must be signed in to change notification settings - Fork 0
/
8Chapter.js
executable file
·85 lines (57 loc) · 1.15 KB
/
8Chapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// PROBLEM 1
function MultiplicatorUnitFailure() {
this.message = 'Failed to multiply';
}
function primitiveMultiply(num1, num2) {
if (Math.random() < 0.50) {
return num1 * num2;
} else {
throw new MultiplicatorUnitFailure();
}
}
function reliablyMultiply(num1, num2) {
let hasError = false;
do {
try {
console.log(primitiveMultiply(num1, num2));
hasError = false;
}
catch(error) {
if (error instanceof MultiplicatorUnitFailure) {
console.log(error.message);
hasError = true;
}
else {
hasError = false;
throw error;
}
}
} while (hasError);
}
reliablyMultiply(8, 8);
// PROBLEM 2
const box = {
locked: true,
unlock: function() { this.locked = false; },
lock: function() { this.locked = true; },
_content: [],
get content() {
if (this.locked) throw new Error("Locked!");
return this._content;
}
};
function withBoxUnlocked(func) {
const locked = box.locked;
if (locked) box.unlock();
try {
func(box.content);
console.log(box.content);
}
catch (error) {
console.log(error);
}
finally {
if (locked) box.lock();
}
}
// withBoxUnlocked(array => array.push("Vladic Kostin"));