Update Graph.

This commit is contained in:
Oleksii Trekhleb 2018-05-07 11:06:37 +03:00
parent ddf149b0d8
commit 50df3bf717
4 changed files with 52 additions and 2 deletions

View File

@ -110,6 +110,12 @@ export default class Graph {
return null; return null;
} }
getWeight() {
return this.getAllEdges().reduce((weight, graphEdge) => {
return weight + graphEdge.weight;
}, 0);
}
toString() { toString() {
return Object.keys(this.vertices).toString(); return Object.keys(this.vertices).toString();
} }

View File

@ -4,7 +4,7 @@ export default class GraphEdge {
* @param {GraphVertex} endVertex * @param {GraphVertex} endVertex
* @param {number} [weight=1] * @param {number} [weight=1]
*/ */
constructor(startVertex, endVertex, weight = 1) { constructor(startVertex, endVertex, weight = 0) {
this.startVertex = startVertex; this.startVertex = startVertex;
this.endVertex = endVertex; this.endVertex = endVertex;
this.weight = weight; this.weight = weight;

View File

@ -174,4 +174,48 @@ describe('Graph', () => {
expect(edges[0]).toEqual(edgeAB); expect(edges[0]).toEqual(edgeAB);
expect(edges[1]).toEqual(edgeBC); expect(edges[1]).toEqual(edgeBC);
}); });
it('should calculate total graph weight for default graph', () => {
const graph = new Graph();
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeAD = new GraphEdge(vertexA, vertexD);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeAD);
expect(graph.getWeight()).toBe(0);
});
it('should calculate total graph weight for weighted graph', () => {
const graph = new Graph();
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 1);
const edgeBC = new GraphEdge(vertexB, vertexC, 2);
const edgeCD = new GraphEdge(vertexC, vertexD, 3);
const edgeAD = new GraphEdge(vertexA, vertexD, 4);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeAD);
expect(graph.getWeight()).toBe(10);
});
}); });

View File

@ -10,7 +10,7 @@ describe('GraphEdge', () => {
expect(edge.getKey()).toBe('A_B'); expect(edge.getKey()).toBe('A_B');
expect(edge.startVertex).toEqual(startVertex); expect(edge.startVertex).toEqual(startVertex);
expect(edge.endVertex).toEqual(endVertex); expect(edge.endVertex).toEqual(endVertex);
expect(edge.weight).toEqual(1); expect(edge.weight).toEqual(0);
}); });
it('should create graph edge with predefined weight', () => { it('should create graph edge with predefined weight', () => {