HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Find number matching range

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rangenumbermatchingfind

Problem

I have code that checks the range of a value and sets a variable accordingly.

if ( 169 <= angle && angle < 191 ) {currentOrientation = "1";}
if ( 191 <= angle && angle < 214 ) {currentOrientation = "2";}
if ( 214 <= angle && angle < 236 ) {currentOrientation = "3";}
if ( 236 <= angle && angle < 259 ) {currentOrientation = "4";}
if ( 259 <= angle && angle < 281 ) {currentOrientation = "5";}
if ( 281 <= angle && angle < 304 ) {currentOrientation = "6";}
if ( 304 <= angle && angle < 326 ) {currentOrientation = "7";}
if ( 326 <= angle && angle < 349 ) {currentOrientation = "8";}
if ( 349 <= angle) {currentOrientation = "9";}
if ( angle < 11 ) {currentOrientation = "9";}
if ( 11 <= angle && angle < 34 ) {currentOrientation = "10";}
if ( 34 <= angle && angle < 56 ) {currentOrientation = "11";}
if ( 56 <= angle && angle < 79 ) {currentOrientation = "12";}
if ( 79 <= angle && angle < 101 ) {currentOrientation = "13";}
if ( 101 <= angle && angle < 124 ) {currentOrientation = "14";}
if ( 124 <= angle && angle < 146 ) {currentOrientation = "15";}
if ( 146 <= angle && angle < 169 ) {currentOrientation = "16";}


Each range is 1/16 of 360°. There is a shift so that cardinal values (90,180..) are in the center of the range.

I am curious about how this code can be optimized. Maybe a jQuery function? So far a loop isn't interesting enough if I can't get the values automatically.

Solution

This function has very slightly different boundaries, but you may find it does better than what you have right now:

function degreesToOrientation(degrees){
    return 1 + Math.floor(((Number(degrees) + 180 + 11.25) % 360.0) / 22.5);
}


one sixteenth of a circle is 22.5 degrees. centering that is at 11.25 degrees.

So, you add 11.25 degrees to your angle, rotate it a further 180 degrees, Use the Modulo to bring the value back in to range, then divide it by the size of each segment.

This returns a value from 0 through 15 (for the 16 segments). So, add 1 to get your 'orientation'.

It does not care about the degree amount as long as it is greater than -191.25 ... to start with... (the modulo operation is funny with negative numbers...)

Here is a jfiddle

Code Snippets

function degreesToOrientation(degrees){
    return 1 + Math.floor(((Number(degrees) + 180 + 11.25) % 360.0) / 22.5);
}

Context

StackExchange Code Review Q#36744, answer score: 4

Revisions (0)

No revisions yet.