So I’ve come across some of my old code, which is something like :
const valStore = {
val1: "val1"
val2: "val2"
val3: "val3"
}
And it then is calls this like so:
switch (val) {
case "val4":
function()
break;
case "val5":
coolFunction()
break;
case valStore[val]:
otherFunction(val)
...
I don’t like that there is an entire object with identical keys & values it seems messy as it’s only 5 values in the real version, although a fall-through switch statement doesn’t seem much better:
switch (val) {
case "val4":
function()
break;
case "val5":
coolFunction()
break;
case "val1":
case "val2":
case "val3":
otherFunction(val)
...
I’ve considered using sets and an else if, I’m not sure about if I want a replacement or if I’m wasting my time. It just got me thinking.
2
Answers
Alternatively to the
switch
, you could put the function references in the object and invoke them directly:I would also suggest finding a way to remove the
valX: otherFunction
duplication, but without knowing the context and structure of your logic it’s difficult to suggest a workable alternative.it would be best to use a dictionary with functions instead of
switch
orif else
statementsLanguage
there are two ways to do language
Version 1
have each language then its string value for said text
Version 2
have each string and its language version
I Prefer
Version 2