# Is there a better way to get a compass point from 140° than a series of if's?

This JavaScript converts degrees to a compass point, e.g. convert.toCompass(140) gets 140° -> SE.

I can't help think: is there a more concise way to do this?

var convert = {
toCompass: function(degrees)
{
if(degrees >= 0 && degrees <= 11.25)
{
return 'N';
}

else if(degrees > 11.25 && degrees <= 33.75)
{
return 'NNE';
}

else if(degrees > 33.75 && degrees <= 56.25)
{
return 'NE';
}

else if(degrees > 56.25 && degrees <= 78.75)
{
return 'ENE';
}

else if(degrees > 78.75 && degrees <= 101.25)
{
return 'E';
}

else if(degrees > 101.25 && degrees <= 123.75)
{
return 'ESE';
}

else if(degrees > 123.75 && degrees <= 146.25)
{
return 'SE';
}

else if(degrees > 146.25 && degrees <= 168.75)
{
return 'SSE';
}

else if(degrees > 168.75 && degrees <= 191.25)
{
return 'S';
}

else if(degrees > 191.25 && degrees <= 213.75)
{
return 'SSW';
}

else if(degrees > 213.75 && degrees <= 236.25)
{
return 'SW';
}

else if(degrees > 236.25 && degrees <= 258.75)
{
return 'WSW';
}

else if(degrees > 258.75 && degrees <= 281.25)
{
return 'W';
}

else if(degrees > 281.25 && degrees <= 303.75)
{
return 'WNW';
}

else if(degrees > 303.75 && degrees <= 326.25)
{
return 'NW';
}

else if(degrees > 326.25 && degrees <= 348.75)
{
return 'NNW';
}

else if(degrees > 348.75 && degrees <= 360)
{
return 'N';
}
}
}

-
THis question is very similar to another question here. There is a fair amount of discussion on that other question whihc may be useful to you too: codereview.stackexchange.com/questions/36744/… – rolfl Jan 5 '14 at 12:25

By looking at values in your series of if's, you can make an array ([]), then calculate which index to pick:

var convert = {
toCompass: function(degrees)
{
return ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'][Math.round(degrees / 11.25 / 2)];
}
}



JSFiddle demo

-
I'd throw in a % 360 to be defensive. – 200_success Jan 5 '14 at 9:22