4
\$\begingroup\$

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

I can't help but 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';
        }
    }
}
\$\endgroup\$
1

1 Answer 1

7
\$\begingroup\$

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)];
    }
}

alert(convert.toCompass(140));      // SE

JSFiddle demo

\$\endgroup\$
1
  • 7
    \$\begingroup\$ I'd throw in a % 360 to be defensive. \$\endgroup\$ Jan 5, 2014 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.