mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-07-05 08:26:14 +08:00
Add Prim.
This commit is contained in:
@ -110,12 +110,18 @@ export default class Graph {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {number}
|
||||
*/
|
||||
getWeight() {
|
||||
return this.getAllEdges().reduce((weight, graphEdge) => {
|
||||
return weight + graphEdge.weight;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string}
|
||||
*/
|
||||
toString() {
|
||||
return Object.keys(this.vertices).toString();
|
||||
}
|
||||
|
@ -19,4 +19,11 @@ export default class GraphEdge {
|
||||
|
||||
return `${startVertexKey}_${endVertexKey}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string}
|
||||
*/
|
||||
toString() {
|
||||
return this.getKey();
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,9 @@
|
||||
import LinkedList from '../linked-list/LinkedList';
|
||||
|
||||
export default class GraphVertex {
|
||||
/**
|
||||
* @param {*} value
|
||||
*/
|
||||
constructor(value) {
|
||||
if (value === undefined) {
|
||||
throw new Error('Graph vertex must have a value');
|
||||
@ -37,6 +40,13 @@ export default class GraphVertex {
|
||||
return edges.map(neighborsConverter);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {GraphEdge[]}
|
||||
*/
|
||||
getEdges() {
|
||||
return this.edges.toArray().map(linkedListNode => linkedListNode.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {GraphEdge} requiredEdge
|
||||
* @returns {boolean}
|
||||
|
@ -8,6 +8,7 @@ describe('GraphEdge', () => {
|
||||
const edge = new GraphEdge(startVertex, endVertex);
|
||||
|
||||
expect(edge.getKey()).toBe('A_B');
|
||||
expect(edge.toString()).toBe('A_B');
|
||||
expect(edge.startVertex).toEqual(startVertex);
|
||||
expect(edge.endVertex).toEqual(endVertex);
|
||||
expect(edge.weight).toEqual(0);
|
||||
|
@ -21,17 +21,20 @@ describe('GraphVertex', () => {
|
||||
expect(vertex.toString()).toBe('A');
|
||||
expect(vertex.getKey()).toBe('A');
|
||||
expect(vertex.edges.toString()).toBe('');
|
||||
expect(vertex.getEdges()).toEqual([]);
|
||||
});
|
||||
|
||||
it('should add edges to vertex and check if it exists', () => {
|
||||
const vertexA = new GraphVertex('A');
|
||||
const vertexB = new GraphVertex('A');
|
||||
const vertexB = new GraphVertex('B');
|
||||
|
||||
const edgeAB = new GraphEdge(vertexA, vertexB);
|
||||
vertexA.addEdge(edgeAB);
|
||||
|
||||
expect(vertexA.hasEdge(edgeAB)).toBeTruthy();
|
||||
expect(vertexB.hasEdge(edgeAB)).toBeFalsy();
|
||||
expect(vertexA.getEdges().length).toBe(1);
|
||||
expect(vertexA.getEdges()[0].toString()).toBe('A_B');
|
||||
});
|
||||
|
||||
it('should return vertex neighbors in case if current node is start one', () => {
|
||||
|
Reference in New Issue
Block a user