Skip to content

Commit f367724

Browse files
committed
added documentation to conditionals
1 parent 67ca969 commit f367724

File tree

1 file changed

+90
-4
lines changed

1 file changed

+90
-4
lines changed

‎general-patterns/conditionals.html‎

Lines changed: 90 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,106 @@
1111
*/
1212

1313
// NOTE: Paul Irish states that the first statement is only an antipattern when optimizing for
14-
// low-bandwidth source (such as for a bookmarklet.
14+
// low-bandwidth source (such as for a bookmarklet).
1515
// Using the first statement will generally outperform the regex in a loop, and is faster than the
1616
// object literal for lower numbers of conditions (they generally even out around 10 conditions).
1717
// See http://jsperf.com/if-this-or-that
1818

19-
// antipattern
19+
// Normal Pattern
2020
if(type==='foo'||type==='bar'){}
2121

22-
// preferred method 1 - regex test
22+
23+
/* alternative method 1 - regex test */
2324
if(/^(foo|bar)$/.test(type)){}
2425

25-
// preferred method 2 - object literal lookup (smaller if < 5 items)
26+
27+
/* alternative method 2 - object literal lookup (smaller if < 5 items) */
2628
if(({foo:1,bar:1})[type]){}
2729

30+
31+
/* alternative method 3 - binary-search-like approach
32+
This approach is best when there are ranges of values for which to test
33+
*/
34+
35+
if(value==0){
36+
returnresult0;
37+
}elseif(value==1){
38+
returnresult1;
39+
}elseif(value==2){
40+
returnresult2;
41+
}elseif(value==3){
42+
returnresult3;
43+
}elseif(value==4){
44+
returnresult4;
45+
}elseif(value==5){
46+
returnresult5;
47+
}elseif(value==6){
48+
returnresult6;
49+
}elseif(value==7){
50+
returnresult7;
51+
}elseif(value==8){
52+
returnresult8;
53+
}elseif(value==9){
54+
returnresult9;
55+
}else{
56+
returnresult10;
57+
}
58+
59+
if(value<6){
60+
if(value<3){
61+
if(value==0){
62+
returnresult0;
63+
}elseif(value==1){
64+
returnresult1;
65+
}else{
66+
returnresult2;
67+
}
68+
}else{
69+
if(value==3){
70+
returnresult3;
71+
}elseif(value==4){
72+
returnresult4;
73+
}else{
74+
returnresult5;
75+
}
76+
}
77+
}else{
78+
if(value<8){
79+
if(value==6){
80+
returnresult6;
81+
}else{
82+
returnresult7;
83+
}
84+
}else{
85+
if(value==8){
86+
returnresult8;
87+
}elseif(value==9){
88+
returnresult9;
89+
}else{
90+
returnresult10;
91+
}
92+
}
93+
}
94+
95+
96+
/* alternative method 4 - object/array lookup tables
97+
Most useful when there is logical mapping between a single key and a single value
98+
*/
99+
100+
if(value==0){
101+
returnresult0;
102+
}elseif(value==1){
103+
returnresult1;
104+
}elseif(value==2){
105+
returnresult2;
106+
}
107+
108+
// define the array of results
109+
varresults=[result0,result1,result2];
110+
// return the correct result
111+
returnresults[value];
112+
113+
28114
// reference
29115
// http://paulirish.com/2009/perf/
30116
</script>

0 commit comments

Comments
(0)