|
| 1 | +import {Graph} from '../../../../data-structures/graph/graph'; |
| 2 | +import {GraphVertex} from '../../../../data-structures/graph/graphVertex'; |
| 3 | +import {GraphEdge} from '../../../../data-structures/graph/graphEdge'; |
| 4 | +import {depthFirstSearch} from '../depthFirstSearch'; |
| 5 | + |
| 6 | +test('should perform BFS on graph', () => { |
| 7 | + const graph = new Graph(true); |
| 8 | + |
| 9 | + const vertexA = new GraphVertex('A'); |
| 10 | + const vertexB = new GraphVertex('B'); |
| 11 | + const vertexC = new GraphVertex('C'); |
| 12 | + const vertexD = new GraphVertex('D'); |
| 13 | + const vertexE = new GraphVertex('E'); |
| 14 | + const vertexF = new GraphVertex('F'); |
| 15 | + const vertexG = new GraphVertex('G'); |
| 16 | + const vertexH = new GraphVertex('H'); |
| 17 | + |
| 18 | + const edgeAB = new GraphEdge(vertexA, vertexB); |
| 19 | + const edgeBC = new GraphEdge(vertexB, vertexC); |
| 20 | + const edgeCG = new GraphEdge(vertexC, vertexG); |
| 21 | + const edgeAD = new GraphEdge(vertexA, vertexD); |
| 22 | + const edgeAE = new GraphEdge(vertexA, vertexE); |
| 23 | + const edgeEF = new GraphEdge(vertexE, vertexF); |
| 24 | + const edgeDH = new GraphEdge(vertexD, vertexH); |
| 25 | + |
| 26 | + graph |
| 27 | + .addEdge(edgeAB) |
| 28 | + .addEdge(edgeBC) |
| 29 | + .addEdge(edgeCG) |
| 30 | + .addEdge(edgeAD) |
| 31 | + .addEdge(edgeAE) |
| 32 | + .addEdge(edgeEF) |
| 33 | + .addEdge(edgeDH); |
| 34 | + |
| 35 | + expect(graph.toString()).toBe('A,B,C,G,D,E,F,H'); |
| 36 | + |
| 37 | + const enterVertexCallback = jest.fn(); |
| 38 | + const leaveVertexCallback = jest.fn(); |
| 39 | + |
| 40 | + // Traverse graphs without callbacks first. |
| 41 | + depthFirstSearch(graph, vertexA); |
| 42 | + |
| 43 | + // Traverse graph with enterVertex and leaveVertex callbacks. |
| 44 | + depthFirstSearch(graph, vertexA, { |
| 45 | + enterVertex: enterVertexCallback, |
| 46 | + leaveVertex: leaveVertexCallback, |
| 47 | + }); |
| 48 | + |
| 49 | + expect(enterVertexCallback).toHaveBeenCalledTimes(8); |
| 50 | + expect(leaveVertexCallback).toHaveBeenCalledTimes(8); |
| 51 | +}); |
0 commit comments