Rectangle class, equals method returns incorrect value

Hi,

recently I’ve used Rectangle’s equals() method and found that it incorrectly returns false when both rectangles are the same. Problem occurs when any of the properties of the Rectangle are NaN (not a number).


See the example:

var a:Rectangle = new Rectangle();
var b:Rectangle = new Rectangle();
var c:Rectangle = new Rectangle(0, 0, NaN, 0);
var d:Rectangle = new Rectangle(0, 0, NaN, 0);
var e:Rectangle = d;
trace("a.equals(b) = " + a.equals(b));//a.equals(b) = true
trace("c.equals(d) = " + c.equals(d));//c.equals(d) = false
trace("c.equals(d) = " + d.equals(e));//c.equals(d) = false
trace("e.equals(a) = " + e.equals(a));//e.equals(a) = false

According to flash help, the equals() method:

Determines whether the object specified in the toCompare parameter is equal to this Rectangle object. This method compares the x, y, width, and height properties of an object against the same properties of this Rectangle object.

But because comparison of NaN always returns false:

following code

trace(NaN == NaN);

will produce following error

Warning: Illogical comparison with NaN. This statement always evaluates to false.

this method can’t correctly compare it, the solution would be to use custom equals() method (or fixing the Rectangle implementation):


		/**
		 * Compares properties (x,y,width,height) of given Rectangle objects and returns true when both match. This method includes comparing NaN values.
		 * @param	a
		 * @param	b
		 * @return
		 */
		protected function compareRect(a:Rectangle, b:Rectangle):Boolean
		{
			if (a === b) return true;

			if (isNaN(a.x) != isNaN(b.x)) return false;
			if (!isNaN(a.x) && !isNaN(b.x) && a.x != b.x) return false;
			if (isNaN(a.y) != isNaN(b.y)) return false;
			if (!isNaN(a.y) && !isNaN(b.y) && a.y != b.y) return false;
			if (isNaN(a.width) != isNaN(b.width)) return false;
			if (!isNaN(a.width) && !isNaN(b.width) && a.width != b.width) return false;
			if (isNaN(a.height) != isNaN(b.height)) return false;
			if (!isNaN(a.height) && !isNaN(b.height) && a.height != b.height) return false;
			
			return true;
		}

and the same example again using our custom method:

var a:Rectangle = new Rectangle();
var b:Rectangle = new Rectangle();
var c:Rectangle = new Rectangle(0, 0, NaN, 0);
var d:Rectangle = new Rectangle(0, 0, NaN, 0);
var e:Rectangle = d;

trace("compareRect(a,b) = " + compareRect(a,b));//compareRect(a,b) = true
trace("compareRect(c,d) = " + compareRect(c,d));//compareRect(c,d) = true
trace("compareRect(d,e) = " + compareRect(d,e));//compareRect(d,e) = true
trace("compareRect(a,e) = " + compareRect(a, e));//compareRect(a,e) = false

Happy Coding.

This entry was posted in actionscript, bugs, flash and tagged , , , , . Bookmark the permalink.

1 Response to Rectangle class, equals method returns incorrect value

  1. WoW,

    Its Cool, thanks for sharing

Comments are closed.