-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjectCompare.js
More file actions
51 lines (49 loc) · 1.66 KB
/
objectCompare.js
File metadata and controls
51 lines (49 loc) · 1.66 KB
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
/** objectCompare() takes two objects, which could be an array or
* object literal, containing nested arrays and/or object literals.
*
* returns true if all values in the objects are the same and in the same order
* returns false if not.
*/
function objectCompare(obj1, obj2) {
if (Array.isArray(obj1) !== Array.isArray(obj2)) return false;
if (!Array.isArray(obj1) && !Array.isArray(obj2)) {
obj1 = Object.values(obj1);
obj2 = Object.values(obj2);
}
if (obj1.length !== obj2.length) return false;
for (let i = 0; i < obj1.length; i++) {
if (typeof obj1[i] === 'object' && typeof obj2[i] === 'object') {
if (!objectCompare(obj1[i], obj2[i])) return false;
} else {
if (obj1[i] !== obj2[i]) {
return false;
}
}
}
return true;
}
/** Alternative version with worse runtime (recursively loops through both objects completely,
* even if there is a mismatch in the first pair of values)
*
function objectCompare1(obj1, obj2) {
/** flatten() recursively pushes elements/values of the nested arrays/objects
* into a values array and returns values array.
function flatten(obj, values = []) {
if (typeof obj === 'object' && !Array.isArray(obj)) {
for (let key in obj) {
if (typeof obj[key] === 'object') values = flatten(obj[key], values);
else values.push(obj[key]);
}
} else if (Array.isArray(obj)) {
for (let elem of obj) {
if (typeof elem === 'object') values = flatten(elem, values);
else values.push(elem);
}
}
return values;
}
if (flatten(obj1).join('') === flatten(obj2).join('')) return true;
else return false;
}
*/
module.exports = objectCompare;