Deep Equals

webdev122

WebDev

Posted on July 18, 2022

Deep Equals

Instructions

Write a function that will take in two items of any type. The function should perform a deep equality

Inputs: Any, Any Output: Boolean

Solution
This problem has several parts. Let’s walk through it logically.

  1. comparing NaN with NaN using -- or --- will always return false. Because of this, we need to start by checking if both inputs are NaN.
  2. If the items are of a different type, we can immediately return false.
  3. If they’re the same type and not objects, we can return the result of a simple equality operation using ===. We have to be careful to include null here, as typeof null returns object. This is due to a bug in JavaScript (http://2£tlity.cDm/2013/10/typeof-null.html) itself.
  4. We need to be careful to ensure that both objects have the same number of properties. If they don’t, return false.
  5. Now we need to go through every key and make sure they’re the same on every object. To do this, we can loop through the first object and check to make sure that the second object has matching values.
  6. If all checks have passed, return true

Let’s transform that pseudocode into code.

function deepEquals(a, b) {
  if(Number.isNaN(a) && Number.isNaN(b)) {
    return true;
  }

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

  if(typeof a !== 'object' || a === null || b === null) {
    return a === b;
  }

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

  for(const key in a) {
    if(!deepEqualS(a[key], b[key])) {
     return false;
    }
  } 

  return true;
}
Enter fullscreen mode Exit fullscreen mode

Time

Our function has to go through and process every property of both items. Assuming that the two inputs are deeply equivalent, we can say that the time complexity is:

0(n).

Space
This is a recursive function and the number of calls will generally scale with the objects’ sizes, so:

0(n).

💖 💪 🙅 🚩
webdev122
WebDev

Posted on July 18, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related