[SOLVED] Utility method --> If (VALUE is within SIGMA range of TARGET) return true. Very helpful!


(Helios) #1

is there any way to condense:

if (value > target + deviation  && value < target - deviation){
    doStuff();
}

down to something like:

if (value == Math.range(target, sigmaDeviation))
{
    doStuff();
}

(Zachary Lewis) #2

There isn’t a function (that I’m aware of) that will do this, but that’s never stopped us before!

/**
 * Is a value within the range of a target?
 * @param  value The value to check.
 * @param  target The desired value.
 * @param  range The allowed range of deviation from the target.
 * @return true if the value is with the range of the target; otherwise, returns false.
 */
public function range(value:Number, target:Number, range:Number):Boolean
{
  // Determine if the value is outside the given range and return the
  // negated output.
  
  // Instead of checking to see if the value is within the range,
  // checking to see if the value is outside of the range allows the
  // conditional statement to exit early.

  return !(value < target - range || target + range > value);
}

And yes, I’m aware that there are a bunch of comments for a one-line function, but this function makes you way more attractive to people who have to use your code than

public function isR(v:Number, t:Number, r:Number):Boolean {
  return !(v < t - r || v > t + r);
}

Like, what even is that?


(Helios) #3

Hah! I know the feeling!

Also, clever trick with short circuiting the check. Thanks again, Zach!


(Ultima2876) #5

Could always submit a pull request to get that into the FP class.