* @param {GraphEdge} edge * @returns {Graph}
(edge)
| 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 |