Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way of writing a function that returns the name of an image based on the argument of the function?

Tags:

javascript

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.

like image 534
Bobimaru Avatar asked Jul 30 '19 14:07

Bobimaru


2 Answers

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"));
like image 125
nick zoum Avatar answered Oct 04 '22 03:10

nick zoum


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"));
like image 35
Danmoreng Avatar answered Oct 04 '22 01:10

Danmoreng