๐Ÿ’พdeepEqual()

JS โŸฉ value โŸฉ function โŸฉ recursive โŸฉ deepEqual()

returns true only if they are

  • the same value or

  • objects with properties of the same keys/values, where the values are compared with a recursive call to deepEqual.

function deepEqual(a, b) {

    // check if `value` is (non-function) object
    function isNonFunctionObject(value) {
        return typeof value === 'object' && value !== null;
    }

    // 1. same value -> always equal
    if (a === b) return true;

    // 2. a !== b

    // 2.1 (either one is primitive/function) different values -> always unequal
    if(!isNonFunctionObject(a) || !isNonFunctionObject(b)) return false;

    // 2.2 both (non-function, different) objects
    
    // - count properties
    const keysA = Object.keys(a), keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    // - check property keys/values
    for (const key of keysA) {
        if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
    }

    // - property keys/values all match
    return true;
}

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

// test
let obj = {
    x: {y: "a"}, 
    z: 2,
};

[
  [x => x, x => x],	        // โจ‰ (different functions)
  [obj, obj],			// โ—‹ (same object)
  [obj, {x: 1, z: 2}],	        // โจ‰
  [obj, {x: {y: "a"}, z: 2}],	// โ—‹
  [1, 2],			// โจ‰
  [1, 1],			// โ—‹
  [obj, 1],			// โจ‰
  [{x: undefined}, {}],	        // โจ‰
  
].forEach(([a,b]) => {
  console.log(deepEqual(a,b))   // โœ… test "deepEqual"
});

Last updated