/
switch-pattern.html
69 lines (62 loc) · 1.72 KB
/
switch-pattern.html
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: switch Pattern
Description: improve the readability and robustness of your switch statements
*/
/* Style conventions:
* 1. Aligning each `case` with `switch` (an exception to the curly braces indentation rule).
* 2. Indenting the code within each case.
* 3. Ending each `case` with a clear `break`;.
* 4. Avoiding fall-throughs (when you omit the break intentionally). If you're absolutely convinced
* that a fall-through is the best approach, make sure you document such cases, because they might
* look like errors to the readers of your code.
* 5. Ending the `switch` with a `default`: to make sure there's always a sane result even if none of
* the cases matched.
*/
//antipattern
var inspect_me = 0,
result = '';
switch (inspect_me) {
case 0:
result = "zero";
break;
case 1:
result = "one";
break;
default:
result = "unknown";
}
//preferred 1,
//'cause it is much faster and easy to reuse and read
//avoid to use switch
var results = {
0: "zero",
1: "one"
};
result = results[inspect_me] || "unknown";
//preferred 2
var resultFuncs = {
0: function () {
//some code for "zero" case
return "zero";
},
1: function () {
//some code for one case
return "one";
}
};
result = (resultFuncs[inspect_me] || function () {
//some code for default case
return "unknown";
})();
// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
</script>
</body>
</html>