mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-07-06 01:15:56 +08:00
Add getNeighbors method to Graph.
This commit is contained in:
@ -25,6 +25,13 @@ export default class Graph {
|
|||||||
return this.vertices[vertexKey];
|
return this.vertices[vertexKey];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {GraphVertex} vertex
|
||||||
|
*/
|
||||||
|
getNeighbors(vertex) {
|
||||||
|
return vertex.getNeighbors();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {GraphEdge} edge
|
* @param {GraphEdge} edge
|
||||||
* @returns {Graph}
|
* @returns {Graph}
|
||||||
|
@ -111,4 +111,25 @@ describe('Graph', () => {
|
|||||||
expect(graphEdgeAB).toEqual(edgeAB);
|
expect(graphEdgeAB).toEqual(edgeAB);
|
||||||
expect(graphEdgeAB.weight).toBe(10);
|
expect(graphEdgeAB.weight).toBe(10);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should return vertex neighbors', () => {
|
||||||
|
const graph = new Graph(true);
|
||||||
|
|
||||||
|
const vertexA = new GraphVertex('A');
|
||||||
|
const vertexB = new GraphVertex('B');
|
||||||
|
const vertexC = new GraphVertex('C');
|
||||||
|
|
||||||
|
const edgeAB = new GraphEdge(vertexA, vertexB);
|
||||||
|
const edgeAC = new GraphEdge(vertexA, vertexC);
|
||||||
|
|
||||||
|
graph
|
||||||
|
.addEdge(edgeAB)
|
||||||
|
.addEdge(edgeAC);
|
||||||
|
|
||||||
|
const neighbors = graph.getNeighbors(vertexA);
|
||||||
|
|
||||||
|
expect(neighbors.length).toBe(2);
|
||||||
|
expect(neighbors[0]).toEqual(vertexB);
|
||||||
|
expect(neighbors[1]).toEqual(vertexC);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
Reference in New Issue
Block a user