I have an object which has a property called tier
which has 9 possible values - IRON, BRONZE, SILVER, GOLD, PLATINUM, DIAMOND, MASTER, GRANDMASTER and CHALLENGER
.
Based on that property, I want to display the emblem corresponding to the tier, however, whilst the tier might be called IRON
, the image file with the emblem would be called Emblem_Iron
.
This is why I've created a function which takes a tier
as an argument and then returns the file name of the emblem image corresponding to the tier
so that I could do this:
<img class='ranked-emblem' :src="'../emblems/' + rankedEmblem(league.tier) + '.png'" alt="">
And my function is:
rankedEmblem(tier){
if (tier === 'IRON') {
return 'Emblem_Iron'
} else if (tier === 'BRONZE') {
return 'Emblem_Bronze'
} else if (tier === 'SILVER') {
return 'Emblem_Silver'
} else if (tier === 'GOLD') {
return 'Emblem_Gold'
} else if (tier === 'PLATINUM') {
return 'Emblem_Platinum'
} else if (tier === 'DIAMOND') {
return 'Emblem_Diamond'
} else if (tier === 'MASTER') {
return 'Emblem_Master'
} else if (tier === 'GRANDMASTER') {
return 'Emblem_Grandmaster'
} else if (tier === 'CHALLENGER') {
return 'Emblem_Challenger'
}
}
While this works completely fine, I was wondering if there's a more elegant way of doing this that would shorten the function and maybe remove a couple of if els.
You can use a plain Object
as a map.
var emblems = {
IRON: "Emblem_Iron",
BRONZE: "Emblem_Bronze",
SILVER: "Emblem_Silver",
GOLD: "Emblem_Gold",
PLATINUM: "Emblem_Platinum",
DIAMOND: "Emblem_Diamond",
MASTER: "Emblem_Master",
GRANDMASTER: "Emblem_Grandmaster",
CHALLENGER: "Emblem_Challenger"
};
function rankedEmblem(tier) {
// Could also help user by doing: emblems[tier.toUpperCase()]
return emblems[tier] || "No_Emblem";
}
console.log(rankedEmblem("GOLD"));
console.log(rankedEmblem("PLATINUM"));
You can use String concatination and functions like so:
function rankedEmblem(tier){
return "Emblem_" + tier.charAt(0).toUpperCase() + tier.slice(1).toLowerCase();
}
console.log(rankedEmblem("CHALLENGER"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With