0

I am currently running tests using Mocha to check equality for both objects, arrays, and objects inside of arrays. My last test is currently failing even though in my "objects" portion of my tests, I pass in two similar objects and they pass.

const compareObjects = function(a, b){

  for(var prop in a){
    if(a[prop] === b[prop] !== true){
      return false;
    }
  }
  return true;
}

const compareArrays = function(a, b){

  if(a.length !== b.length){
    return false;
  }

  for(var i = 0; i < a.length; i++){

    //checking for objects inside of arrays here
    if(typeof a[i] === 'object' && typeof b[i] === 'object'){
      if(compareObjects(a[i], b[i]) !== true){
        return false;
      }
    } else if (a[i] !== b[i]){
      return false;
    }
  }

  return true;
}

This fails -

  describe('Arrays', function() {
    it('should return false when comparing two objects inside of 
    arrays with different number of keys', function() {

      var arr1 = [
        {
          name: 'Janet',
          age: 25,
        }
      ]
      var arr2 = [
        {
          name: 'Janet',
          age: 25,
          hairColor: 'brown'
        }
      ]

      assert.equal(false, compareArrays(arr1, arr2));
    });

  });

This passes -

  describe('Objects', function() {
    it('should return false when there is a different number of 
    keys', function() {

      var obj1 = {name: 'Janet', age: 25, hair: 'brown'}
      var obj2 = {name: 'Janet', age: 25}

      assert.equal(false, compareObjects(obj1, obj2));
    });
 }); 
FakeEmpire
  • 668
  • 1
  • 14
  • 35
  • `(a[i] !== b[i])` will always pass, since the operands are not referring to the same object. – Teemu Jul 31 '17 at 21:07
  • 1
    CompareObjects only iterates through the properties in A and checks that the same property in B exists. You should also compare `Object.keys(a).length` to `Object.keys(b).length` – James Jul 31 '17 at 21:14

1 Answers1

0

Cheat! Use JSON.stringify and compare strings.

const a = {
  foo: "foo",
  bar: "bar",
  foobar: {
    says: "meow"
  }
};
const b = {
  foo: "foo",
  bar: "bar",
  foobar: {
    says: "meow"
  }
};
const c = {
  foo: "foo",
  bar: "baz",
  foobar: {
    says: "meow"
  }
};

const compareObjects = function(a, b) {
  for (var prop in a) {
    if (a[prop] === b[prop] !== true) {
      return false;
    }
  }
  return true;
}

const compareObjectsCheat = function(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

console.log(compareObjects(a, b));
console.log(compareObjects(a, c));

console.log(compareObjectsCheat(a, b));
console.log(compareObjectsCheat(a, c));
Will
  • 3,201
  • 1
  • 19
  • 17