Last active
May 18, 2023 19:05
-
-
Save vitalii-komenda/e29a0147e2ef6ba620debae7e17dce1c to your computer and use it in GitHub Desktop.
convert currency into another via USD currency
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
convert_currency = (rates, from, to) => { | |
const conversions = {}; | |
// 1.45 / (0.0070 * 110) | |
for(let i=0; i<rates.length; i++) { | |
if (!conversions[rates[i][0]]) { | |
conversions[rates[i][0]] = {}; | |
} | |
conversions[rates[i][0]][rates[i][1]] = rates[i][2]; | |
} | |
for(let i=0; i<rates.length; i++) { | |
if (!conversions.usd[rates[i][1]]) { | |
conversions.usd[ rates[i][1] ] = (rates[i][2] * conversions.usd[ rates[i][0] ]) | |
} | |
} | |
console.log(conversions); | |
if (conversions[from]?.[to]) return conversions[from][to]; | |
if (to === 'usd') return 1 / conversions.usd[from]; | |
return conversions.usd[to] / conversions.usd[from]; | |
}; | |
convert_currency([ | |
['usd', 'jpy', 110], | |
['usd', 'aud', 1.45], | |
['jpy', 'gbp', 0.0070]], | |
'gbp', | |
'usd' | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment