8ball-media

little pieces from everything

Comparing Objects using JSON in AS3

I recently stumbled over a post on josh buhler’s blog regarding the comparison of two objects in AS3 using the ByteArray-class. You can read the post here.

This brought me to an idea.. Instead of comparing each byte in a loop why not using a serialized string and a strict comparison ?

so here we go..

package {

    import com.adobe.serialization.json.JSON;
    import com.adobe.serialization.json.JSONParseError;

    /**
     * class containing useful helper methods
     * @author  david linse (davidlinse@8ball-media.com)
     * @date  2009/21/08
     */
    public class ObjectUtil {

    /**
     * compares given objects and returns boolean
     * result of compare action
     *
     * @param obj1  object
     * @param obj2  object
     * @return  result  boolean true when identical; false otherwise
     */
    static public function compare (obj1:Object, obj2:Object): Boolean {

        try {
            var value1: String = JSON.encode(obj1);
            var value2: String = JSON.encode(obj2);
        }
        catch (e:JSONParseError) {
            trace('[ERROR] ObjectUtil.compare() - '+ e.text);
            return false;
        }

        return (value1 === value2);
    }
}

This was the class, let’s go to a little usage sample..

  //-- an object and a reference to it
  var foo: Object = {label:"hi, i'am foo.."};
  var bar: Object = foo;

  ObjectUtil.compare(foo, bar);   //-- result: true

  //-- two identical objects
  var foo1: Object = {label:"hi, i'am foo.."};
  var bar1: Object = {label:"hi, i'am foo.."};

  ObjectUtil.compare(foo1, bar1);   //-- result: true

  //-- two different objects
  var foo2: Object = {label:"hi, i'am foo.."};
  var bar2: Object = {label:"howdy, i'am bar.."};

  ObjectUtil.compare(foo2, bar2);   //-- result: false

  //-- or more complex objects
  var rect1:Rectangle = new Rectangle (0, 0, 100, 100);
  var rect2:Rectangle = new Rectangle (0, 0, 100, 100);

  ObjectUtil.compare(rect1, rect2);   //-- result: true

  //-- or more complex objects
  var rect3:Rectangle = new Rectangle (0, 0, 100, 100);
  var rect4:Rectangle = new Rectangle (0, 0, 100, 200);

  ObjectUtil.compare(rect3, rect4);   //-- result: false

works as expected.. what did you think ? feel free to use and reply as well.