mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 15:11:16 +08:00
Update Graph.
This commit is contained in:
parent
ddf149b0d8
commit
50df3bf717
@ -110,6 +110,12 @@ export default class Graph {
|
||||
return null;
|
||||
}
|
||||
|
||||
getWeight() {
|
||||
return this.getAllEdges().reduce((weight, graphEdge) => {
|
||||
return weight + graphEdge.weight;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
toString() {
|
||||
return Object.keys(this.vertices).toString();
|
||||
}
|
||||
|
@ -4,7 +4,7 @@ export default class GraphEdge {
|
||||
* @param {GraphVertex} endVertex
|
||||
* @param {number} [weight=1]
|
||||
*/
|
||||
constructor(startVertex, endVertex, weight = 1) {
|
||||
constructor(startVertex, endVertex, weight = 0) {
|
||||
this.startVertex = startVertex;
|
||||
this.endVertex = endVertex;
|
||||
this.weight = weight;
|
||||
|
@ -174,4 +174,48 @@ describe('Graph', () => {
|
||||
expect(edges[0]).toEqual(edgeAB);
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
@ -10,7 +10,7 @@ describe('GraphEdge', () => {
|
||||
expect(edge.getKey()).toBe('A_B');
|
||||
expect(edge.startVertex).toEqual(startVertex);
|
||||
expect(edge.endVertex).toEqual(endVertex);
|
||||
expect(edge.weight).toEqual(1);
|
||||
expect(edge.weight).toEqual(0);
|
||||
});
|
||||
|
||||
it('should create graph edge with predefined weight', () => {
|
||||
|
Loading…
Reference in New Issue
Block a user