Skip to content

Instantly share code, notes, and snippets.

@eduardomoroni
Created July 9, 2020 09:32
Show Gist options
  • Save eduardomoroni/1f9477b2366e5c1b9e01d93e6930e0de to your computer and use it in GitHub Desktop.
Save eduardomoroni/1f9477b2366e5c1b9e01d93e6930e0de to your computer and use it in GitHub Desktop.
challenge
function findRoutes(routes) {
const { sourcesMap, destinationsMap } = createRoutesMaps(routes);
const startingPoint = findStartingPoint(sourcesMap, routes);
const agentRoute = simulateRouteFrom(startingPoint, destinationsMap);
return agentRoute.join(', ');
}
function simulateRouteFrom(startingPoint, destinationsMap) {
const routes = [startingPoint];
let destination = startingPoint;
while (destination) {
destination = destinationsMap.get(destination);
if (destination) {
routes.push(destination);
}
}
return routes;
}
function findStartingPoint(sourcesMap, routes) {
for (const [source] of routes) {
if (!sourcesMap.has(source)) {
return source;
}
}
}
function createRoutesMaps(routes) {
const sourcesMap = new Map();
const destinationsMap = new Map();
routes.forEach(route => {
const [source, destination] = route;
sourcesMap.set(destination, source);
destinationsMap.set(source, destination);
});
return { sourcesMap, destinationsMap };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment