Skip to content

Commit d692c32

Browse files
Time: 47 ms (98.32%), Space: 43.5 MB (76.99%) - LeetHub
1 parent 56f24d7 commit d692c32

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {object} obj1
3+
* @param {object} obj2
4+
* @return {object}
5+
*/
6+
function objDiff(obj1, obj2) {
7+
// If both are primitives(not objects), return empty if they equal else show difference
8+
if (!isObject(obj1) && !isObject(obj2)) {
9+
return obj1 === obj2 ? {} : [obj1, obj2];
10+
}
11+
12+
// If one is primitive and other is object
13+
if (!isObject(obj1) || !isObject(obj2)) {
14+
return [obj1, obj2];
15+
}
16+
17+
// If one is array and the other is object
18+
if (Array.isArray(obj1) !== Array.isArray(obj2)) {
19+
return [obj1, obj2];
20+
}
21+
22+
// If both array or both object, then recursion
23+
const diff = {};
24+
25+
for (const key in obj1) {
26+
// look for obj1 keys present in obj2 (common keys)
27+
if (obj2.hasOwnProperty(key)) {
28+
const result = objDiff(obj1[key], obj2[key]);
29+
// console.log('result: ' + result);
30+
// check if result object we get is empty or not
31+
if (Object.keys(result).length > 0) {
32+
diff[key] = result;
33+
}
34+
}
35+
}
36+
return diff;
37+
38+
function isObject(obj) {
39+
return typeof obj === 'object' && obj !== null;
40+
}
41+
}

0 commit comments

Comments
 (0)