Skip to content

Instantly share code, notes, and snippets.

@beatak
Created April 26, 2012 15:52
Show Gist options
  • Save beatak/2500537 to your computer and use it in GitHub Desktop.
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.
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