Skip to content

Instantly share code, notes, and snippets.

@ohaal
Last active October 17, 2016 08:28
Show Gist options
  • Save ohaal/0aeab4b967843c00e32f3b7ec6ffd42d to your computer and use it in GitHub Desktop.
Save ohaal/0aeab4b967843c00e32f3b7ec6ffd42d to your computer and use it in GitHub Desktop.
Convert currencies in a message to any other currency
function getValuesAndCurrencies(message) {
var regex = /([$|€|£])? ?(\d+(?:[,.]\d{1,2})?) ?(k)? ?\b(NOK|SEK|USD|CAD|EUR|GBP)?\b/gi;
var symbolToCurrency = { "$": "USD", "€": "EUR", "£": "GBP" };
var match, value, currency;
var result = [];
while (match = regex.exec(message)) {
value = parseFloat(match[2].replace(",", ".")) * (match[3].toLowerCase() == "k" ? 1000 : 1);
currency = (match[4] || symbolToCurrency[match[1]]) || "";
result.push([value, currency]);
}
return result;
}
function convertToCurrency(value, fromCurrency, toCurrencyArr) {
return toCurrencyArr.map(toCurrency => queryExternalCurrencyService(value, fromCurrency, toCurrency) + " " + toCurrency);
}
// this is obviously just pseudo
function queryExternalCurrencyService(value, fromCurrency, toCurrency) {
var fakeConversions = { "USD": 8, "EUR": 8, "GBP": 9, "CAD": 6, "SEK": 1, "NOK": 1 };
return (value / fakeConversions[fromCurrency]) * fakeConversions[toCurrency];
}
// this is obviously just pseudo
function onMessage(message) {
getValuesAndCurrencies(message).forEach(valueCurrency => {
var fromValue = valueCurrency[0];
var fromCurrency = valueCurrency[1];
var toCurrencies = ["USD", "NOK", "SEK", "GBP", "CAD", "EUR"].filter(curr => curr != fromCurrency);
console.log(fromValue + " " + fromCurrency + " = " + convertToCurrency(fromValue, fromCurrency, toCurrencies).join(", "));
});
}
onMessage("this is $500 in a sentence, but also 50k NOK so much!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment