1 | import getRate from './lib/get-rate.js';
|
2 | import parse from './utils/parser.js';
|
3 | /**
|
4 | * Function, which converts currencies based on provided rates.
|
5 | *
|
6 | * @param {number | string} amount - Amount of money you want to convert.
|
7 | * @param {Object} options - Conversion options.
|
8 | * @param {new (value: BigSource) => Big} fn - Optional, Big.js constructor - useful to avoid floating point errors.
|
9 | * @return {number} Conversion result.
|
10 | *
|
11 | * @example
|
12 | * const rates = {
|
13 | * GBP: 0.92,
|
14 | * EUR: 1.00,
|
15 | * USD: 1.12
|
16 | * };
|
17 | *
|
18 | * convert(10, {from: 'EUR', to: 'GBP', base: 'EUR', rates}); //=> 9.2
|
19 | */
|
20 | export default function convert(amount, { from, to, base, rates, BigJs }) {
|
21 | // If provided `amount` is a string, use parsing
|
22 | if (typeof amount === 'string') {
|
23 | const data = parse(amount);
|
24 | amount = data.amount;
|
25 | from = data.from ?? from;
|
26 | to = data.to ?? to;
|
27 | }
|
28 | if (BigJs) {
|
29 | return new BigJs(amount).times(getRate(base, rates, from, to)).toNumber();
|
30 | }
|
31 | return (amount * 100) * getRate(base, rates, from, to) / 100;
|
32 | }
|