Skip to content

Instantly share code, notes, and snippets.

@mr-moon
Created Dec 16, 2011
Embed
What would you like to do?
/**
* Evaluates the given number against array of numbers, and returns
* the one that is the "closest"
* @param value Value to be tested
* @param array Array of numbers
* @param method uint a comparison method. 0 - round, 1 - ceil, 2 - floor
* @return The closest value from <code>array</code> parameter
*/
public static function closestAgainstArray(value:Number, array:Array, method:uint = 0):Number
{
var d:Number = Infinity, o:Number = 0, f:Number, l:Number, n:Number, c:Number, t:uint, i:uint;
if (method == 0) {
for each (n in array) {
c = Math.abs(value - n);
if (c <= d) {
d = c;
o = n;
}
}
} else {
t = array.length;
f = c = array[0];
l = array[t - 1];
if (value <= f) return f;
if (value >= l) return l;
if (method == 1) {
for (i = 1; i < t; i++) {
n = array[i];
if (c < value && value <= n) {
return n;
}
c = n;
}
} else if (method == 2) {
for (i = 1; i < array.length; i++) {
n = array[i];
if (c <= value && value < n) {
return c;
}
c = n;
}
} else {
throw new Error('only methods 0, 1 and 2 are supported');
}
}
return o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment