Created
April 26, 2012 15:52
-
-
Save beatak/2500537 to your computer and use it in GitHub Desktop.
give a value and lookup array, and returns the closest value in the array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getRoundupValue = function (val, table) { | |
var result; | |
if (val <= table[0]) { | |
result = table[0]; | |
} | |
else if (val >= table[table.length - 1]) { | |
result = table[table.length - 1]; | |
} | |
else { | |
var v1, v0, d0, d1; | |
loop:for (var i = 1, len = table.length; i < len; ++i) { | |
v1 = table[i]; | |
v0 = table[i - 1]; | |
if (v1 == val) { | |
result = val; | |
break loop; | |
} | |
else if (v1 > val) { | |
d1 = v1 - val; | |
d0 = val - v0; | |
if (d1 < d0) { | |
result = v1; | |
} | |
else { | |
result = v0 | |
} | |
break loop; | |
} | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment