Skip to content

Instantly share code, notes, and snippets.

@ihopeudie
Last active January 30, 2022 14:41
Show Gist options
  • Save ihopeudie/b0c304bd23c1f947fae135a1d9002fb4 to your computer and use it in GitHub Desktop.
Save ihopeudie/b0c304bd23c1f947fae135a1d9002fb4 to your computer and use it in GitHub Desktop.
hyperskill project Simple Currency Converter (Frontend path)
const readline = require('readline');
const ROUND_TO_DIGITS = 4;
const COMMAND_CONVERT = 1;
const COMMAND_EXIT = 2;
const GREETING = 'Welcome to Currency Converter!';
const rates = getRates();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getRates() {
return new Map([
['USD', 1.0],
['JPY', 113.5],
['EUR', 0.89],
['RUB', 74.36],
['GBP', 0.75]
]);
}
function printMap() {
rates
.forEach((k, v) => console.log(`1 USD equals ${k} ${v}`));
}
function readCurrency(label) {
return new Promise((resolve => {
rl.question(`${label}:`, (answer) => {
if (!rates.has(answer.toUpperCase())) {
console.log('Unknown currency');
process.exit(1)
}
resolve(answer.toUpperCase());
});
}))
}
function readAmount() {
return new Promise((resolve => {
rl.question("Amount:", (answer) => {
const num = Number(answer);
if (isNaN(num) || num < 1) {
console.log("The amount can not be less than 1");
process.exit(1)
}
resolve(num);
});
}))
}
async function readCommand() {
console.log(`What do you want to do?
1-Convert currencies 2-Exit program`);
return new Promise((resolve => {
rl.question("", (answer) => {
resolve(Number(answer));
});
}))
}
async function askData() {
while (true) {
const command = await readCommand();
if (!command || (command !== COMMAND_CONVERT && command !== COMMAND_EXIT)) {
console.log("Unknown input");
continue;
}
if (command === COMMAND_CONVERT) {
const from = await readCurrency("From");
const to = await readCurrency("To");
const amount = await readAmount();
const k = ((1 / rates.get(from)) * rates.get(to));
const result = (amount * k)
.toFixed(ROUND_TO_DIGITS);
console.log(`Result: ${amount} ${from} equals ${result} ${to}`)
} else {
process.exit(0)
}
}
}
function main() {
console.log(GREETING);
printMap();
askData();
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment