Skip to content

Commit 3b2f291

Browse files
authored
added object/array compare utils.
1 parent 92e450b commit 3b2f291

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

compare.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
const compareArrays = (arrayA, arrayB) => {
2+
let isEqual = true;
3+
4+
if (arrayA == null && arrayB === null) {
5+
return true;
6+
}
7+
8+
if (arrayA.length !== arrayB.length) {
9+
return false;
10+
}
11+
12+
for (var index = 0; index < arrayA.length; index++) {
13+
const elementA = arrayA[index];
14+
const elementB = arrayB[index];
15+
16+
if (typeof elementA !== typeof elementB) {
17+
isEqual = false;
18+
break;
19+
}
20+
21+
if (Array.isArray(elementA)) {
22+
isEqual &= compareArrays(elementA, elementB);
23+
} else if (typeof elementA === "object") {
24+
isEqual &= compareObjects(elementA, elementB);
25+
} else {
26+
isEqual &= elementA === elementB;
27+
}
28+
29+
if (!isEqual) {
30+
break;
31+
}
32+
}
33+
34+
return isEqual;
35+
};
36+
37+
// yes JSON.stringify(objA) === JSON.stringify(objB) works for shallow comapare, but doesn't work for deep compare!
38+
const compareObjects = (objA, objB) => {
39+
if (objA === null && objB === null) {
40+
return true;
41+
}
42+
const objAKeys = Object.keys(objA);
43+
const objBKeys = Object.keys(objB);
44+
45+
if (objAKeys.length !== objBKeys.length) {
46+
return false;
47+
}
48+
49+
return objAKeys.reduce((isEqual, keyA) => {
50+
const elemA = objA[keyA];
51+
const elemB = objB[keyA];
52+
isEqual &= typeof elemA === typeof elemA;
53+
54+
if (Array.isArray(elemA)) {
55+
isEqual &= compareArrays(elemA, elemB);
56+
} else if (typeof elemA === "object") {
57+
isEqual &= compareObjects(elemA, elemB);
58+
} else {
59+
isEqual &= elemA === elemB;
60+
}
61+
62+
return isEqual;
63+
}, true);
64+
};

0 commit comments

Comments
 (0)