Created
May 18, 2023 19:06
-
-
Save vitalii-komenda/b79f97211b65fb7231fd12d83993e511 to your computer and use it in GitHub Desktop.
convert-currency-via-any
This file contains 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 main = () => { | |
findExchangeRate([['USD', 'JPY', 110],['USD', 'AUD', 1.45],['JPY', 'GBP', 0.0070]], ['GBP', 'AUD'], 1) | |
} | |
const findExchangeRate = (rates, toFrom, value) => { | |
const to = toFrom[1]; | |
const from = toFrom[0]; | |
// build rate graph record | |
const ratesGraph = {} | |
rates.map(rate => { | |
if(!ratesGraph[rate[0]]) ratesGraph[rate[0]] = {}; | |
if(!ratesGraph[rate[1]]) ratesGraph[rate[1]] = {}; | |
ratesGraph[rate[0]][rate[1]] = rate[2]; | |
ratesGraph[rate[1]][rate[0]] = 1 / rate[2]; | |
}) | |
const visited = {} | |
console.log(ratesGraph) | |
console.log('res', findExchangeRateHelper(from, to, value, visited, ratesGraph)); | |
} | |
const findExchangeRateHelper = (from, to, value, visited, ratesGraph) => { | |
const currentRate = value; | |
const queue = []; | |
Object.keys(ratesGraph[from]).forEach(child => { | |
queue.unshift([child, currentRate * ratesGraph[from][child] ]); | |
}); | |
console.log(from); | |
while (queue.length > 0) { | |
const [currentNode, finalRate] = queue.pop(); | |
if(currentNode === to) return finalRate; | |
if(!ratesGraph[currentNode]) return -1; | |
console.log(currentNode, finalRate); | |
visited[currentNode] = true; | |
Object.keys(ratesGraph[currentNode]).forEach(child => { | |
const rate = ratesGraph[currentNode][child]; | |
if(!visited[child]) queue.unshift([child, finalRate * rate]); | |
}); | |
} | |
return -1; | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment