Skip to content

Instantly share code, notes, and snippets.

@vitalii-komenda
Last active May 18, 2023 19:05
Show Gist options
  • Save vitalii-komenda/e29a0147e2ef6ba620debae7e17dce1c to your computer and use it in GitHub Desktop.
Save vitalii-komenda/e29a0147e2ef6ba620debae7e17dce1c to your computer and use it in GitHub Desktop.
convert currency into another via USD currency
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