-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path6-switch.js
More file actions
52 lines (44 loc) · 926 Bytes
/
6-switch.js
File metadata and controls
52 lines (44 loc) · 926 Bytes
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
'use strict';
// Use switch
const getDay = (n) => {
switch (n) {
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
case 7:
return 'Sunday';
default:
return new Error(`Invalid day number: ${n}`);
}
};
console.log(getDay(2));
// Use collection
const days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
const getDayWithoutSwitch = (n) =>
n > 0 && n <= days.length
? days[n - 1]
: new Error(`Invalid day number: ${n}`);
const getDayNumber = (name) => {
const n = days.indexOf(name);
return n !== -1 ? n + 1 : new Error(`Invalid day name: ${name}`);
};
console.log(getDayWithoutSwitch(2));
console.log(getDayWithoutSwitch(20));
console.log(getDayNumber('Sunday'));