4

I'm sure there probably is, however I'm not sure what it's called so apologises if this is something super similar. I'm wondering if there's a faster way to code the following:

var b = "#ff0002";
var o = "#46c029";
var i = "#f2ec00";
var n = "#f64c98";
var g = "#52c6f3";

if(a==1){
    return b;
}else if(a==2){
    return o;
}else if(a==3){
    return i;
}else if(a==4){
    return n;
}else if(a==5){
    return g;
}
2
  • 2
    It's called a switch statement. Or potentially a lookup map would also work. Commented Jul 24, 2018 at 15:31
  • 2
    There's no loop here. Loops are for and while, where you do something repeatedly until some ending condition is met. Commented Jul 24, 2018 at 16:09

2 Answers 2

14

Yeah, lookup array:

return [b, o, i, n, g][a - 1];

Not necessarily faster, but definetly shorter :)

Sign up to request clarification or add additional context in comments.

5 Comments

Amazing! So much cleaner, thank you. Yeah, I wasn't expecting it to be faster but knew it could be clean
@liam glad to help :)
any reason the first letter wouldn't be getting a colour set? :/ I've included the entire script in case it's being caused by a different issue
@liam in your original question, a was 1 to get b, but now your count starts with 0, in that case, just remove the - 1
@liam no worries :)
2

If you have large number of strings to compare from use Object like this:

myObj = {1: '#ff0002', 2: '#46c029', 3: "#f2ec00", 4: "#f64c98", 5: "#52c6f3"}

console.log(myObj[3]);

If you are using ES6 you can use Map() like this:

const myMap = new Map([[1, '#ff0002'], [2, '#46c029'], [3, "#f2ec00"], [4, "#f64c98"], [5, "#52c6f3"]])

console.log(myMap.get(3)); // or any key

3 Comments

But what about 'boing' :P Nah, if this is actually faster I'd be interested, otherwise it's a lengthier script
@Liam if you don't have large number of strings/comparison go with the Jonas W's solution.
No worries, thank you! This is handy though as I started this thread to cover my future tracks when I expand into more numbers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.