-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (67 loc) · 2.35 KB
/
index.js
File metadata and controls
69 lines (67 loc) · 2.35 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const diip = (a, b) => {
const diff = (original, successor) => {
// get types
let originalType = Object.prototype.toString.call(original);
let successorType = Object.prototype.toString.call(successor);
// reject when different types
if (originalType !== successorType) {
return false;
}
// functions are never considered equal
if (originalType === '[object Function]') {
return false;
}
// compare two objects or arrays
if (originalType === '[object Object]' || originalType === '[object Array]') {
let keys = Object.keys(original);
let newKeys = Object.keys(successor);
// creating union of both arrays of keys
if (originalType === '[object Array]') {
let lengthDifference = newKeys.length - keys.length;
if (lengthDifference > 0) {
for (let i = lengthDifference; i > 0; --i) {
keys.push(newKeys[newKeys.length - i]);
}
}
} else {
let keysObj = {};
keys.forEach((key) => {
keysObj[key] = true;
});
newKeys.forEach((key) => {
if (!keysObj[key]) {
keys.push(key);
}
});
}
return keys.reduce((accumulator, key) => {
let temp = diff(original[key], successor[key]);
if (temp !== true) {
if (typeof accumulator === 'boolean') {
accumulator = [];
}
if (temp === false) {
accumulator.push([key]);
} else {
temp.forEach((current) => {
current.unshift(key);
accumulator.push(current);
});
}
}
return accumulator;
}, true);
}
// compare primitive types
return original === successor;
};
let result = diff(a, b);
if (result === true) {
return null;
} else if (result === false) {
return [[]];
}
return result;
};
module.exports = diip;