Skip to content

Commit 8bbdd35

Browse files
authored
Create 2628-json-deep-equal.js
1 parent 54bcc8a commit 8bbdd35

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

javascript/2628-json-deep-equal.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {any} o1
3+
* @param {any} o2
4+
* @return {boolean}
5+
*/
6+
var areDeeplyEqual = function(o1, o2) {
7+
if (o1 === null || o2 === null) {
8+
return o1 === o2;
9+
}
10+
if (typeof o1 !== typeof o2) {
11+
return false;
12+
}
13+
if (typeof o1 !== 'object') { // primitives
14+
return o1 === o2;
15+
}
16+
17+
if (Array.isArray(o1) && Array.isArray(o2)) { // Arrays
18+
if (o1.length !== o2.length) {
19+
return false;
20+
}
21+
for (let i = 0; i < o1.length; i++) {
22+
if (!areDeeplyEqual(o1[i], o2[i])) {
23+
return false;
24+
}
25+
}
26+
} else if (!Array.isArray(o1) && !Array.isArray(o2)) { // Objects
27+
if (Object.keys(o1).length !== Object.keys(o2).length) {
28+
return false;
29+
}
30+
for (const key in o1) {
31+
if (!areDeeplyEqual(o1[key], o2[key])) {
32+
return false;
33+
}
34+
}
35+
} else {
36+
return false;
37+
}
38+
return true;
39+
};

0 commit comments

Comments
 (0)