In this post I’m going to show you one possible solution of one of the 10 Days of JavaScript challenges from Hackerrank. We’re going to use switch statement to return a letter depending on the first letter of provided string.
Challenge
Full description of the challenge: 10 Days of JavaScript. Day 2: switch. I really recommend registering and trying these challenges by yourself.
“Complete the getLetter(s)
function in the editor. It has one parameter: a string, s, consisting of lowercase English alphabetic letters (i.e., a
through z
). It must return A
, B
, C
, or D
depending on the following criteria:
- If the first character in string s is in the set {a, e, i, o, u}, then return
A
. - If the first character in string s is in the set {b, c, d, f, g} , then return
B
. - If the first character in string s is in the set {h, j, k, l, m} , then return
C
. - If the first character in string s is in the set {n, p, q, r, s, t, v, w, x, y, z}, then return
D
.”
Solution and explanation
The first solution is simple and self explanatory:
But it’s also not pretty. I mean it’s not terrible but I’m not happy with it. I would rather use something shorter. Also, it would be nice if sets of letters where grouped (so I don’t have to provide every letter separately). It can be achieved by below code:
The tricky thing of course is switch(true). It makes the switch statement look for the first “true” case. It’s bit confusing and my impression is that it’s a bit forced. For that you could use if-else which feels like a natural solution for this kind of problem. The challenge was about switch usage though, so I’ve used switch.