MCPcopy
hub / github.com/trekhleb/javascript-algorithms / addEdge

Method addEdge

src/data-structures/graph/Graph.js:61–96  ·  view source on GitHub ↗

* @param {GraphEdge} edge * @returns {Graph}

(edge)

Source from the content-addressed store, hash-verified

59 * @returns {Graph}
60 */
61 addEdge(edge) {
62 // Try to find and end start vertices.
63 let startVertex = this.getVertexByKey(edge.startVertex.getKey());
64 let endVertex = this.getVertexByKey(edge.endVertex.getKey());
65
66 // Insert start vertex if it wasn't inserted.
67 if (!startVertex) {
68 this.addVertex(edge.startVertex);
69 startVertex = this.getVertexByKey(edge.startVertex.getKey());
70 }
71
72 // Insert end vertex if it wasn't inserted.
73 if (!endVertex) {
74 this.addVertex(edge.endVertex);
75 endVertex = this.getVertexByKey(edge.endVertex.getKey());
76 }
77
78 // Check if edge has been already added.
79 if (this.edges[edge.getKey()]) {
80 throw new Error('Edge has already been added before');
81 } else {
82 this.edges[edge.getKey()] = edge;
83 }
84
85 // Add edge to the vertices.
86 if (this.isDirected) {
87 // If graph IS directed then add the edge only to start vertex.
88 startVertex.addEdge(edge);
89 } else {
90 // If graph ISN'T directed then add the edge to both vertices.
91 startVertex.addEdge(edge);
92 endVertex.addEdge(edge);
93 }
94
95 return this;
96 }
97
98 /**
99 * @param {GraphEdge} edge

Callers 15

reverseMethod · 0.95
addSameEdgeTwiceFunction · 0.95
deleteNotExistingEdgeFunction · 0.95
primFunction · 0.95
kruskalFunction · 0.95
Graph.test.jsFile · 0.45
dijkstra.test.jsFile · 0.45

Calls 3

getVertexByKeyMethod · 0.95
addVertexMethod · 0.95
getKeyMethod · 0.45

Tested by 3

addSameEdgeTwiceFunction · 0.76
deleteNotExistingEdgeFunction · 0.76