by ankurdhama · 10y ago · 0 comments
function getColor(str){
if(str=='blue'){ return '#0000ff'; }
if(str=='red') { return '#ff0000'; }
}
getColor = {
blue: '#0000ff',
red: '#ffoooo'
}
The second one also has if statements inside the implementation of the hash map, but it isn't actually polluting your business logic. The question is no longer "what do you do when the input is like this or like that", but "lookup the corresponding output".The distinction is nice because I know that getColor[thing] will likely have no side effects. I can treat it, on a theoretical level, strictly as a map.
Of course if the problem is "implement this on a machine without branching" this isn't super useful but most problems are not that.
Edit: The conditional abstractions like map are useful in the sense that the conditions that they support are very simple, in case of map it is if supplied key equals that key, whereas if/else statements can be used to create any kind of complex conditions.