Deep Value

Benchmark created on


Setup

function isObject(value){
  return typeof value === 'object' && value !== null && value !== undefined;
}

function deepEqual(obj1, obj2) {
  const stack = [[obj1, obj2]];

  while (stack.length > 0) {
    const popped = stack.pop();
    if (popped === undefined) return false;

    const [current1, current2] = popped;

    // assume both are raw values
    if (current1 === current2) continue;

    // if above is false, check if both are valid objects (or arrays)
    if (!isObject(current1) || !isObject(current2)) {
      return false;
    }

    const keys1 = Object.keys(current1);
    const keys2Set = new Set(Object.keys(current2));

    if (keys1.length !== keys2Set.size) return false;

    // traverse over each key and push values under the key to the stack
    for (let i = 0; i < keys1.length; i += 1) {
      const key = keys1[i];
      if (!keys2Set.has(key)) return false;

      stack.push([current1[key], current2[key]]);
    }
  }

  return true;
}

export const isDeepEqual = (obj1, obj2) => {
  for (const objectKey in obj1) {
    if (isObject(obj1[objectKey])) {
      if (isDeepEqual(obj1[objectKey], obj2[objectKey])) {
        continue;
      } else {
        return false;
      }
    }

    if (JSON.stringify(obj1[objectKey]) !== JSON.stringify(obj2[objectKey])) {
      return false;
    }
  }
  return true;
};

const objOne = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    street: "123 Main St",
    zipcode: "10001"
  },
  hobbies: ["Reading", "Hiking", "Cooking"],
  friends: [
    {
      name: "Emily",
      age: 24,
      address: {
        city: "Chicago",
        street: "789 Oak St",
        zipcode: "60601"
      },
      hobbies: ["Photography", "Yoga", "Gardening"]
    },
    {
      name: "Mike",
      age: 27,
      address: {
        city: "Los Angeles",
        street: "456 Elm St",
        zipcode: "90001"
      },
      hobbies: ["Painting", "Swimming", "Traveling"]
    }
  ]
};

const objTwo = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    street: "123 Main St",
    zipcode: "10001"
  },
  hobbies: ["Reading", "Hiking", "Cooking"],
  friends: [
    {
      name: "Emily",
      age: 24,
      address: {
        city: "Chicago",
        street: "789 Oak St",
        zipcode: "60601"
      },
      hobbies: ["Photography", "Yoga", "Gardening"]
    },
    {
      name: "Mike",
      age: 27,
      address: {
        city: "Los Angeles",
        street: "456 Elm St",
        zipcode: "90001"
      },
      hobbies: ["Painting", "Swimming", "Traveling"]
    }
  ]
};

Test runner

Ready to run.

Testing in
TestOps/sec
deepEqual
deepEqual(objOne, objTwo)
ready
isDdeepEqual
isDdeepEqual(objOne, objTwo)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.