|
| 1 | +/** |
| 2 | + * 2628. JSON Deep Equal |
| 3 | + * https://leetcode.com/problems/json-deep-equal/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given two values o1 and o2, return a boolean value indicating whether two values, o1 and o2, |
| 7 | + * are deeply equal. |
| 8 | + * |
| 9 | + * For two values to be deeply equal, the following conditions must be met: |
| 10 | + * - If both values are primitive types, they are deeply equal if they pass the === equality check. |
| 11 | + * - If both values are arrays, they are deeply equal if they have the same elements in the same |
| 12 | + * order, and each element is also deeply equal according to these conditions. |
| 13 | + * - If both values are objects, they are deeply equal if they have the same keys, and the |
| 14 | + * associated values for each key are also deeply equal according to these conditions. |
| 15 | + * |
| 16 | + * You may assume both values are the output of JSON.parse. In other words, they are valid JSON. |
| 17 | + * |
| 18 | + * Please solve it without using lodash's _.isEqual() function |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {null|boolean|number|string|Array|Object} o1 |
| 23 | + * @param {null|boolean|number|string|Array|Object} o2 |
| 24 | + * @return {boolean} |
| 25 | + */ |
| 26 | +var areDeeplyEqual = function(o1, o2) { |
| 27 | + if (o1 === o2) return true; |
| 28 | + if (o1 == null || o2 == null) return false; |
| 29 | + if (typeof o1 !== 'object' || typeof o2 !== 'object') return false; |
| 30 | + |
| 31 | + if (Array.isArray(o1) !== Array.isArray(o2)) return false; |
| 32 | + |
| 33 | + if (Array.isArray(o1)) { |
| 34 | + if (o1.length !== o2.length) return false; |
| 35 | + return o1.every((item, index) => areDeeplyEqual(item, o2[index])); |
| 36 | + } |
| 37 | + |
| 38 | + const keys1 = Object.keys(o1); |
| 39 | + const keys2 = Object.keys(o2); |
| 40 | + if (keys1.length !== keys2.length) return false; |
| 41 | + |
| 42 | + return keys1.every(key => keys2.includes(key) && areDeeplyEqual(o1[key], o2[key])); |
| 43 | +}; |
0 commit comments