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