When should I use something like this versus a regular Switch statement? What are the pros and cons of each?
function ABC(i, j, a) {
var ops = {
'add': function(i, j) { return i + j; },
'minus': function(i, j) { return i - j; },
'multiply': function(i, j) { return i * j; },
'random': function(i, j) {
return ops[['add', 'minus', 'multiply'][Math.floor(Math.random() * 3)]](i, j);
}
};
return ops[a](i, j);
}
Pros:
It is much more flexible. You can define the functions anywhere, and you can reassign them at runtime, or even generate the dictionary programatically, which is a big win if there are patterns that you can factor out. You can also reuse the dictionary later, or pass it around.
Cons:
In a compiled language, it’s likely slower. (With a JIT it shouldn’t really matter.)
For small code snippets, the switch version is more readable.
Personally I’d prefer the dict approach, but then again I code primarily in Python.