Created
July 9, 2020 09:32
-
-
Save eduardomoroni/1f9477b2366e5c1b9e01d93e6930e0de to your computer and use it in GitHub Desktop.
challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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