-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy path8-foolproof.js
59 lines (51 loc) · 1.24 KB
/
8-foolproof.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
'use strict';
// Antipattern: Fool-proof code
// Assumption: idiots will pass anything to my function
{
const max = (...args) => {
if (args.length !== 2) {
throw new Error('Function expects two aruments');
}
const a = args.shift();
if (typeof a !== 'number') {
throw new Error('Unexpected type of first arument');
}
const b = args.shift();
if (typeof b !== 'number') {
throw new Error('Unexpected type of second arument');
}
return a > b ? a : b;
};
// Usage 1
console.log(`Max of 10 and 20 is ${max(10, 20)}`);
// Usage 2
const a = new Number(10);
const b = new Number(20);
console.log(`Max of ${a} and ${b} is ${max(a, b)}`);
// Usage 3
const x = {
[Symbol.toPrimitive]() {
return 10;
}
};
const y = 20;
console.log(`Max of ${x} and ${y} is ${max(x, y)}`);
}
// Solution
{
const max = (a, b) => (a > b ? a : b);
// Usage 1
console.log(`Max of 10 and 20 is ${max(10, 20)}`);
// Usage 2
const a = new Number(10);
const b = new Number(20);
console.log(`Max of ${a} and ${b} is ${max(a, b)}`);
// Usage 3
const x = {
[Symbol.toPrimitive]() {
return 10;
}
};
const y = 20;
console.log(`Max of ${x} and ${y} is ${max(x, y)}`);
}