|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Нужно создать функцию, которая будет конвертировать передаваемую сумм из одной валюты в другую.. согласно следующих параметров: |
| 4 | +// - сумма для конвертации. |
| 5 | +// - исходная валюта (initial currency). |
| 6 | +// - целевая валюта для конвертации (convert currency). |
| 7 | +// При этом возвращая строку сконвертированной суммы. Если не получилось, то `null`. |
| 8 | +// - на примере 3 валют. |
| 9 | + |
| 10 | +function convert(sum, initialCurrency, convertCurrency) { |
| 11 | + const allCurrencies = [ |
| 12 | + { name: 'USD', mult: 1 }, |
| 13 | + { name: 'RUB', mult: 1 / 60 }, |
| 14 | + { name: 'EUR', mult: 1.1 }, |
| 15 | + ]; |
| 16 | + |
| 17 | + const initial = allCurrencies.find( |
| 18 | + (currency) => currency.name === initialCurrency |
| 19 | + ); |
| 20 | + |
| 21 | + if (!initial) { |
| 22 | + return null; |
| 23 | + } |
| 24 | + |
| 25 | + const convert = allCurrencies.find( |
| 26 | + (currency) => currency.name === convertCurrency |
| 27 | + ); |
| 28 | + |
| 29 | + if (!convert) { |
| 30 | + return null; |
| 31 | + } |
| 32 | + |
| 33 | + return new Intl.NumberFormat('ru-RU', { |
| 34 | + style: 'currency', |
| 35 | + currency: convert.name, |
| 36 | + }).format((sum * initial.mult) / convert.mult); |
| 37 | +} |
| 38 | + |
| 39 | +console.log(convert(10000, 'RUB', 'USD')); // 166,67 $ |
| 40 | +console.log(convert(10000, 'RUB', 'EUR')); // 151,52 € |
| 41 | +console.log(convert(100, 'USD', 'RUB')); // 6 000,00 ₽ |
| 42 | +console.log(convert(100, 'USD', 'EUR')); // 90,91 € |
| 43 | +console.log(convert(100, 'EUR', 'RUB')); // 6 600,00 ₽ |
| 44 | +console.log(convert(100, 'TG', 'RUB')); // null |
| 45 | +console.log(convert(100, 'EUR', 'TG')); // null |
0 commit comments