| 43 | } |
| 44 | |
| 45 | class Graph { |
| 46 | constructor() { |
| 47 | this.nodes = []; |
| 48 | this.adjacencyList = {}; |
| 49 | } |
| 50 | |
| 51 | addNode(node) { |
| 52 | this.nodes.push(node); |
| 53 | this.adjacencyList[node] = []; |
| 54 | } |
| 55 | |
| 56 | addEdge(from, to, weight) { |
| 57 | this.adjacencyList[from].push({ node: to, weight }); |
| 58 | this.adjacencyList[to].push({ node: from, weight }); |
| 59 | } |
| 60 | |
| 61 | findPathWithDijkstra(startNode, endNode) { |
| 62 | let times = {}; |
| 63 | let backtrace = {}; |
| 64 | let pq = new PriorityQueue(); |
| 65 | |
| 66 | times[startNode] = 0; |
| 67 | |
| 68 | this.nodes.forEach((node) => { |
| 69 | if (node !== startNode) { |
| 70 | times[node] = Infinity; |
| 71 | } |
| 72 | }); |
| 73 | // [startingNode, Weight] |
| 74 | pq.enqueue([startNode, 0]); |
| 75 | |
| 76 | while (!pq.isEmpty()) { |
| 77 | let shortestStep = pq.dequeue(); |
| 78 | let currentNode = shortestStep[0]; |
| 79 | |
| 80 | this.adjacencyList[currentNode].forEach((neighbor) => { |
| 81 | let time = times[currentNode] + neighbor.weight; |
| 82 | if (time < times[neighbor.node]) { |
| 83 | times[neighbor.node] = time; |
| 84 | backtrace[neighbor.node] = currentNode; |
| 85 | pq.enqueue([neighbor.node, time]); |
| 86 | } |
| 87 | }); |
| 88 | } |
| 89 | |
| 90 | let path = [endNode]; |
| 91 | let lastStep = endNode; |
| 92 | |
| 93 | while (lastStep !== startNode) { |
| 94 | path.unshift(backtrace[lastStep]); |
| 95 | lastStep = backtrace[lastStep]; |
| 96 | } |
| 97 | |
| 98 | return `Path is ${path} and time is ${times[endNode]}`; |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | let map = new Graph(); |
nothing calls this directly
no outgoing calls
no test coverage detected