-
Notifications
You must be signed in to change notification settings - Fork 0
/
declarative-vs-imperative.js
61 lines (52 loc) · 1.89 KB
/
declarative-vs-imperative.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
//calgarylibrary.ca
29065029066818
09022017
/************************** SIMPLYFYING SWITCH CASE *********************/
var doSomething = function(doWhat) {
switch(doWhat) {
case "doThisThing":
// more code...
break;
case "doThatThing":
// more code...
break;
case "doThisOtherThing":
// more code....
break;
// additional cases here, etc.
default:
// default behavior
break;
}
};
var thingsWeCanDo = {
doThisThing : function() { /* behavior */ },
doThatThing : function() { /* behavior */ },
doThisOtherThing : function() { /* behavior */ },
default : function() { /* behavior */ }
};
var doSomething = function(doWhat) {
var thingToDo = thingsWeCanDo.hasOwnProperty(doWhat) ? doWhat : "default"
thingsWeCanDo[thingToDo]();
};
/************************** SIMPLYFYING SWITCH CASE *********************/
/******************************** PERFORMANCE OPTIMIZATION ***************************/
/*The Bad
The following would be considered inefficient:*/
function something() {
if('something' in obj) {
// something
}
else {
// fallback
}
}
/*The Good
Instead of running the conditional check within every function call, run the conditional before setting the function: */
var something = ('something' in obj) ? function() {
// something
} : function() {
// fallback
};
/*This pattern is especially applicable when using feature detection -- i.e. the value of the conditional never changing. Of course the conditional evaluation is fast but why calculate easy conditionals more than once? You shouldn't, of course. Keep this pattern in mind when creating your own frameworks -- don't repeat code! */
/*The code above is inefficient because the conditional is run upon each call of the function. Let's do better!*/