Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 6f25e24

Browse files
committed
Add solution #2628
1 parent e486edb commit 6f25e24

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1971,6 +1971,7 @@
19711971
2625|[Flatten Deeply Nested Array](./solutions/2625-flatten-deeply-nested-array.js)|Medium|
19721972
2626|[Array Reduce Transformation](./solutions/2626-array-reduce-transformation.js)|Easy|
19731973
2627|[Debounce](./solutions/2627-debounce.js)|Medium|
1974+
2628|[JSON Deep Equal](./solutions/2628-json-deep-equal.js)|Medium|
19741975
2629|[Function Composition](./solutions/2629-function-composition.js)|Easy|
19751976
2630|[Memoize II](./solutions/2630-memoize-ii.js)|Hard|
19761977
2631|[Group By](./solutions/2631-group-by.js)|Medium|

solutions/2628-json-deep-equal.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

Comments
 (0)