Created
December 16, 2011 14:07
-
-
Save mr-moon/1486161 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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