forked from mattphillips/deep-object-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
31 lines (21 loc) · 933 Bytes
/
index.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
import { isDate, isEmpty, isObject, properObject } from '../utils';
const diff = (lhs, rhs) => {
if (lhs === rhs) return {}; // equal return no diff
if (!isObject(lhs) || !isObject(rhs)) return rhs; // return updated rhs
const l = properObject(lhs);
const r = properObject(rhs);
const deletedValues = Object.keys(l).reduce((acc, key) => {
return r.hasOwnProperty(key) ? acc : { ...acc, [key]: undefined };
}, {});
if (isDate(l) || isDate(r)) {
if (l.valueOf() === r.valueOf()) return {};
return r;
}
return Object.keys(r).reduce((acc, key) => {
if (!l.hasOwnProperty(key)) return { ...acc, [key]: r[key] }; // return added r key
const difference = diff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff
return { ...acc, [key]: difference }; // return updated key
}, deletedValues);
};
export default diff;