# deepEqual()

[JS](../../../..) ⟩ [value](../../..) ⟩ [function](../..) ⟩ [recursive]() ⟩ deepEqual()

{% hint style="success" %}
returns true only if they are

* the <mark style="color:yellow;">**same value**</mark> or&#x20;
* <mark style="color:yellow;">**objects**</mark> with properties of the <mark style="color:yellow;">**same keys/values**</mark>, where the values are compared with a <mark style="color:yellow;">**recursive**</mark> call to <mark style="color:purple;">**deepEqual**</mark>.
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
* replit ⟩ [deepEqual(a, b)](https://replit.com/@pegasusroe/deepEquala-b#index.js)

```javascript
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;
}
```

💈範例：&#x20;

```javascript
// 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"
});
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Eloquent JavaScript ⟩&#x20;
  * [ ] Data Structures ⟩ [Deep Comparison](https://eloquentjavascript.net/04_data.html#i_IJBU+aXOIC)
  * [ ] [Recursion](https://eloquentjavascript.net/03_functions.html#h_jxl1p970Fy)
{% endtab %}

{% tab title="📘 手冊" %}
* [ ] [Recursion](https://developer.mozilla.org/en-US/docs/Glossary/Recursion)
{% endtab %}
{% endtabs %}
