1 |
|
2 |
|
3 | import * as R from 'ramda';
|
4 |
|
5 | const isObject = R.compose(R.equals('Object'), R.type);
|
6 | const allAreObjectsOrLists = R.compose(R.either(R.all(isObject), R.all(Array.isArray)), R.values);
|
7 | const hasVersion = versionLabel => obj => R.has(versionLabel, obj);
|
8 | const hasBoth = versionLabels => obj => R.all(versionLabel => hasVersion(versionLabel)(obj), versionLabels);
|
9 | const isEqual = versionLabels => obj => R.both(
|
10 | hasBoth(versionLabels),
|
11 | R.compose(
|
12 | R.apply(R.equals),
|
13 | R.values
|
14 | )
|
15 | )(obj);
|
16 |
|
17 | const markAdded = obj => R.compose(R.append(undefined), R.values)(obj);
|
18 | const markRemoved = obj => R.compose(R.prepend(undefined), R.values)(obj);
|
19 | const isAddition = versionLabels => obj => R.both(
|
20 | hasVersion(R.head(versionLabels)),
|
21 | R.complement(hasVersion(R.last(versionLabels)))
|
22 | )(obj);
|
23 | const isRemoval = versionLabels => obj => R.both(
|
24 | R.complement(
|
25 | hasVersion(R.head(versionLabels))
|
26 | ),
|
27 | hasVersion(R.last(versionLabels))
|
28 | )(obj);
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | export const objectDiff = R.curry((versionLabels, l, r) => {
|
40 | const labels = R.defaultTo(['__left', '__right'], versionLabels);
|
41 | const [left, right] = labels;
|
42 | return R.compose(
|
43 | result => R.map(
|
44 | R.cond([
|
45 | [obj => isAddition(labels)(obj),
|
46 | obj => markAdded(obj)
|
47 | ],
|
48 | [obj => isRemoval(labels)(obj),
|
49 | obj => markRemoved(obj)
|
50 | ],
|
51 | [obj => hasBoth(labels)(obj),
|
52 | obj => R.when(
|
53 | allAreObjectsOrLists,
|
54 |
|
55 |
|
56 | o => R.compose(
|
57 |
|
58 | values => R.apply(objectDiff(versionLabels), values),
|
59 | R.values
|
60 | )(o)
|
61 |
|
62 | )(obj)
|
63 | ]
|
64 | ]
|
65 | ), result),
|
66 | result => R.reject(obj => isEqual(labels)(obj), result),
|
67 | R.useWith(
|
68 | R.mergeWith(R.merge),
|
69 | [
|
70 | R.map(R.objOf(left)),
|
71 | R.map(R.objOf(right))
|
72 | ]
|
73 | )
|
74 | )(l, r);
|
75 | });
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | export const prettyPrintObjectDiff = (versionLabels, l, r) => {
|
85 | return R.compose(
|
86 | result => JSON.stringify(result, null, 2),
|
87 | objectDiff
|
88 | )(versionLabels, l, r);
|
89 | };
|