3 ms·
It seems strange (to me)--maybe in a good way, but would it be preferable to use the JSON literal over the if statement (for the sake of the argument assume in
by cconroy 14y ago
It seems strange (to me)--maybe in a good way, but would it be preferable to use the JSON literal over the if statement (for the sake of the argument assume in javascript if returns a value)?
val =
if (person === "Homer") {
return expr
} else if (person === "Bart") {
return expr
} ...
----
val =
{
"Homer": expr ,
"Bart": expr ,
...
}[person];
Would the literal be simpler because it uses data over syntax, or rules instead of conditionals?
- lucian1900 14y agoI frequently use the latter in Python. I like that it's easy to construct programatically (because it's data) and it more explicitly handles the various cases (especially the default case).
- dpritchett 14y agoAgree, I do it a lot as a way of selecting functions in a switch statement: handlers = { 'dave' : call_dave(), 'ted' : call_ted(), 'julie' : contact('julie') } handlers['dave']() # Call dave handlers['julie']() # Contact julie [handlers[person]() for person in ['dave', 'julie', 'ted']] # Contact all three