Reputation: 9
I'm trying to use a switch statement to convert some shortened tokens into full words, last time I did it, it worked, this time not so much. I think it's something wrong with the types, but I have no idea how to fix it. Weirdly enough, the modifier portion works correctly, but not the source part.
function keyToSource(key)
{
let fullSource, source, modifier;
if(key.includes("-"))
{
modifier = key.substring(key.indexOf("-") + 1, key.length);
source = key.substring(0, key.indexOf("-"));
}
else source = key;
switch(source)
{
case "Bo": fullSource = "Body"; break;
case "Ca": fullSource = "Capture"; break;
case "FA": fullSource = "Forearms"; break;
case "HL": fullSource = "Hindlegs"; break;
case "HS": fullSource = "Hard Shell"; break;
case "IR": fullSource = "Investigation Reward"; break;
case "PB": fullSource = "Palico Bonus"; break;
case "Pl": fullSource = "Plunderblade"; break;
case "SD": fullSource = "Shiny Drop"; break;
case "Ta": fullSource = "Tail"; break;
case "Tr": fullSource = "Track"; break;
default: fullSource = "Error"; break;
}
if(typeof modifier !== 'undefined')
{
switch(modifier)
{
case "C": fullSource += " carve"; break;
case "G": fullSource += "(Gold)"; break;
case "S": fullSource += "(Silver)"; break;
case "W": fullSource += " wound"; break;
default: fullSource = "Error" + fullSource; break;
}
}
return fullSource;
}
console.log(keyToSource("Ta"));
console.log(keyToSource("Ta-C"));
Upvotes: 0
Views: 51
Reputation: 57135
Your code appears to work. However, you can clean up the logic quite a lot by moving your switch statements into objects:
function keyToSource(key) {
const k = key.split("-");
const source = {
"Bo": "Body",
"Ca": "Capture",
"FA": "Forearms",
"HL": "Hindlegs",
"HS": "Hard Shell",
"IR": "Investigation Reward",
"PB": "Palico Bonus",
"Pl": "Plunderblade",
"SD": "Shiny Drop",
"Ta": "Tail",
"Tr": "Track"
};
const modifier = {
"C": " carve",
"G": "(Gold)",
"S": "(Silver)",
"W": " wound"
};
return (source[k[0]] || "") + (modifier[k[1]] || "");
}
console.log(keyToSource("Ta"));
console.log(keyToSource("Ta-C"));
console.log(keyToSource("PB"));
console.log(keyToSource("Ta-G"));
console.log(keyToSource("SD-W"));
console.log(keyToSource("HS-C"));
console.log(keyToSource("as- da-sdf")); // test invalid entry
Feel free to post a clarification if this isn't cutting it for you.
Upvotes: 1