tracktracker/src/tam/routing.js

41 lines
1003 B
JavaScript

import network from "./network.json";
/**
* Find a route linking two nodes or stops.
* @param {string} from ID of the starting stop or node.
* @param {string} to ID of the ending stop or node.
* @return {lineString?} If it exists, a segment linking the two nodes that has
* the least number of nodes possible.
*/
export const findRoute = (from, to) => {
const queue = [from];
const parent = {from: from};
while (queue.length > 0 && !(to in parent)) {
const current = queue.shift();
for (const successor of network.navigation[current].successors) {
if (!(successor in parent)) {
queue.push(successor);
parent[successor] = current;
}
}
}
if (!(to in parent)) {
return null;
}
const path = [];
let current = to;
while (current !== from) {
path.push(current);
current = parent[current];
}
path.push(from);
path.reverse();
return path;
};