Drinks for Drunks
I’m telling you about this kata because ideally you’re an employer who wants to know if I know how to think. I do…I think. Ha! See what I did there?
So “Bartender, drinks!” presented a relatively simple problem: write a function that maps alcoholic beverages to a variety of professions according to a provided table. The table includes six specific professions with corresponding beverages as well as a default beverage, “Beer,” for any other argument.
My brain immediately considered using multiple if…else statements, but that seemed tedious. Then I remembered switch statements, which I’ve seen around but have never really found a reason to use in my own code. I didn’t know if switch statements were considered better, worse, or equal to if…else statements, so I googled it.
The blogs I read generally agreed that switch statements are better if you’ve got more than a handful of conditions. So with seven possible outcomes, switch made more sense than if…else. But during my research, I learned about a technique that avoids conditional logic altogether: dispatch tables.
In Dispatch tables, also called lookup tables or method lookups, you stick all your conditions and resulting functions into an object as key/value pairs, then return the value of whichever key matches the argument provided when the function is called.
So a truncated version of my script would look like this:
For any beginners who stumble across this blog, here’s what’s happening on each line:
Line 1: I’m declaring a function, calling it drinksForDrunks and telling it to take a single argument, which I’ve named “profession.”
Line 2: I need to easily match the provided argument to one of the keys in my object, so I need to eliminate issues with letter cases. I could have set everything to uppercase, but I don’t like yelling in my code, so I went the toLowerCase() route.
Lines 4–13: Using ES6 syntax, I’m declaring a variable, “professions,” and assigning it to an object. The keys in the object are strings that correspond to professions and the values are functions that return whatever booze people in that profession imbibe.
Lines 15–17: I have a default case for arguments that aren’t keys in my object. I’m using bracket notation to check the value at a given key. Each key has a function as its value, so if an argument doesn’t meet this condition, the default behavior is triggered.
Line 19: If the argument matches one of the keys in the object, the function returns whatever value corresponds to that key.
I have no idea what more experienced programmers would think about my solution. I know there is an ongoing argument about whether conditional logic is helpful or harmful to code efficiency. I’m too much of a noob to get into all that. I just wanted to use a technique I’d never seen before. It works.