A not uncommon pattern is to use a dictionary, or array as a lookup table in place of a switch or conditional. In some languages, like Python, there is no switch statement, and dictionaries are the main way to imitate that behavior. In languages like JavaScript, where the line between objects and dictionaries is blurred to the point of non-existence, it’s a common approach. A lot of switch statements can be converted to an object literal with functions as its values, e.g.:
Cassi had a co-worker who was at least peripherally aware of this technique. They might have heard about it, and maybe they saw it used once, from a distance, on a foggy day and their glasses were covered with rain and they also weren’t actually paying attention. When they needed to convert a day, represented as a number from 1–7, into a day-as-a-string, they wrote some code which looks like this:
We’ll get to Yes, it would be simpler to have just done
Simulates a switch statement (with fewer lines of code), they say. In reality, they’ve simulated a lookup table with more lines of code, and as a bonus, this needs to inspect every element (until it finds a match), versus a lookup table which only needs to directly access the match. Whether or not Cassi fixes the I can only assume/hope that Cassi will be switching jobs, shortly. //thedailywtf.com/images/highlight/highlight.pack.js
[Advertisement]
Forget logs. Next time you’re struggling to replicate error, crash and performance issues in your apps – Think Raygun! Installs in minutes. Learn more.
via Tumblr CodeSOD: Switching Daily
0 Comments
Leave a Reply. |
About Us:Dive deep into a topic with Appeared, learning both how and why things work. Come and be a part of our group if you are looking for a collection of articles on software development and computer programming. I am an experienced and enthusiastic computer programmer who prefers high-level languages and simple solutions. Other Profiles:
|