1 |
|
2 | "use strict";
|
3 | import type { JsonGraph, JsonGraphNode, JsonGraphEnvelope } from ".";
|
4 |
|
5 | function mergeJsonGraphNode(
|
6 | left: JsonGraphNode,
|
7 | right: JsonGraphNode
|
8 | ): JsonGraphNode {
|
9 | if (right === null || typeof right !== "object" || right.$type) {
|
10 | return right;
|
11 | }
|
12 | if (left === null || typeof left !== "object" || left.$type) {
|
13 | return left;
|
14 | }
|
15 | return mergeJsonGraph(left, right);
|
16 | }
|
17 |
|
18 | function mergeJsonGraph(left: JsonGraph, right: JsonGraph): JsonGraph {
|
19 | if (left === right) {
|
20 | return right;
|
21 | }
|
22 | const acc: JsonGraph = Object.assign({}, left);
|
23 | for (const key in right) {
|
24 | if (Object.prototype.hasOwnProperty.call(right, key)) {
|
25 | const rightValue = right[key];
|
26 | if (typeof rightValue !== "undefined") {
|
27 | const leftValue = acc[key];
|
28 | if (leftValue !== rightValue) {
|
29 | acc[key] =
|
30 | typeof leftValue !== "undefined"
|
31 | ? mergeJsonGraphNode(leftValue, rightValue)
|
32 | : rightValue;
|
33 | }
|
34 | }
|
35 | }
|
36 | }
|
37 | return acc;
|
38 | }
|
39 |
|
40 | function mergeJsonGraphEnvelope(
|
41 | left: JsonGraphEnvelope,
|
42 | right: JsonGraphEnvelope
|
43 | ): JsonGraphEnvelope {
|
44 | if (
|
45 | left === right ||
|
46 | (left.paths &&
|
47 | left.paths.length === 0 &&
|
48 | !left.invalidated &&
|
49 | !left.context)
|
50 | ) {
|
51 | return right;
|
52 | }
|
53 | const result: JsonGraphEnvelope = {
|
54 | jsonGraph: right.jsonGraph
|
55 | ? mergeJsonGraph(left.jsonGraph, right.jsonGraph)
|
56 | : left.jsonGraph
|
57 | };
|
58 | if (left.paths && right.paths) {
|
59 | result.paths = left.paths.concat(right.paths);
|
60 | }
|
61 | if (right.invalidated) {
|
62 | result.invalidated = left.invalidated
|
63 | ? left.invalidated.concat(right.invalidated)
|
64 | : right.invalidated;
|
65 | } else if (left.invalidated) {
|
66 | result.invalidated = left.invalidated;
|
67 | }
|
68 | if (right.context) {
|
69 | result.context = left.context
|
70 | ? mergeJsonGraph(left.context, right.context)
|
71 | : right.context;
|
72 | } else if (left.context) {
|
73 | result.context = left.context;
|
74 | }
|
75 | return result;
|
76 | }
|
77 |
|
78 | module.exports = { mergeJsonGraph, mergeJsonGraphEnvelope, mergeJsonGraphNode };
|