-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy path3-switch.js
105 lines (95 loc) · 1.73 KB
/
3-switch.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';
// Antipattern: switch
{
const color = (name) => {
switch (name) {
case 'black':
console.log(1);
break;
case 'red':
console.log(2);
break;
case 'green':
console.log(3);
break;
case 'yellow':
console.log(4);
break;
case 'blue':
console.log(5);
break;
case 'magenta':
console.log(6);
break;
case 'cyan':
console.log(7);
break;
case 'white':
console.log(8);
break;
}
console.log('color name:', name);
};
color('white');
}
// Better switch usage
{
const color = (name) => {
switch (name) {
case 'black': return 1;
case 'red': return 2;
case 'green': return 3;
case 'yellow': return 4;
case 'blue': return 5;
case 'magenta': return 6;
case 'cyan': return 7;
case 'white': return 8;
}
};
console.log('white', color('white'));
}
// Use array instead
{
const COLORS = [
/* 1 */ 'black',
/* 2 */ 'red',
/* 3 */ 'green',
/* 4 */ 'yellow',
/* 5 */ 'blue',
/* 6 */ 'magenta',
/* 7 */ 'cyan',
/* 8 */ 'white',
];
const color = (name) => COLORS.indexOf(name) + 1;
console.log('white', color('white'));
}
// Use object instead
{
const COLORS = {
black: 1,
red: 2,
green: 3,
yellow: 4,
blue: 5,
magenta: 6,
cyan: 7,
white: 8,
};
const color = (name) => COLORS[name];
console.log('white', color('white'));
}
// Use Map instead
{
const COLORS = new Map([
['black', 1],
['red', 2],
['green', 3],
['yellow', 4],
['blue', 5],
['magenta', 6],
['cyan', 7],
['white', 8],
]);
const color = (name) => COLORS.get(name);
console.log('white', color('white'));
}