Last active
October 5, 2018 06:34
-
-
Save blackavec/30c6fcda46a54d80febbec1b96c68d51 to your computer and use it in GitHub Desktop.
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
| const routeMap = [ | |
| { from: "A", to: "B", cost: 1 }, | |
| { from: "A", to: "C", cost: 4 }, | |
| { from: "A", to: "D", cost: 10 }, | |
| { from: "B", to: "E", cost: 3 }, | |
| { from: "C", to: "D", cost: 4 }, | |
| { from: "C", to: "F", cost: 2 }, | |
| { from: "D", to: "E", cost: 1 }, | |
| { from: "E", to: "B", cost: 3 }, | |
| { from: "E", to: "A", cost: 2 }, | |
| { from: "F", to: "D", cost: 1 } | |
| ] | |
| function calculator(input) { | |
| if (!input) throw "input is required." | |
| const routes = input.split("-") | |
| if (routes.length < 2) | |
| throw 'route must have destination as follow "A-C", "D-F", "A-F-D"' | |
| let accumulatedCosts = 0 | |
| routes.reduce((prev, current) => { | |
| const route = routeMap.find( | |
| route => route.from === prev.toUpperCase() && route.to === current.toUpperCase() | |
| ) | |
| if (!route) throw "route not found" | |
| accumulatedCosts += route.cost | |
| return current | |
| }) | |
| return accumulatedCosts | |
| } | |
| console.log("result: A-B-E =>", calculator("A-B-E")) | |
| console.log("result: A-D =>", calculator("A-D")) | |
| console.log("result: E-A-C-F =>", calculator("E-A-C-F")) | |
| try { | |
| console.log("result: A-D-F =>", calculator("A-D-F")) | |
| } catch (e) { | |
| console.log("result: A-D-F => no such route") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment