cashify-es2017
Version:
Lightweight currency conversion library, successor of money.js
37 lines (36 loc) • 1.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const has_key_js_1 = require("../utils/has-key.js");
/**
* Get the conversion rate.
* @param base Base currency.
* @param rates Object containing currency rates (for example from an API, such as Open Exchange Rates).
* @param from Currency from which you want to convert.
* @param to Currency to which you want to convert.
* @return Conversion result.
*/
function getRate(base, rates, from, to) {
if (from && to) {
// If `from` equals `to`, return 100% directly
if (from === to) {
return 1;
}
// If `from` equals `base`, return the basic exchange rate for the `to` currency
if (from === base && (0, has_key_js_1.default)(rates, to)) {
return rates[to];
}
// If `to` equals `base`, return the basic inverse rate of the `from` currency
if (to === base && (0, has_key_js_1.default)(rates, from)) {
return 1 / rates[from];
}
// Otherwise, return the `to` rate multipled by the inverse of the `from` rate to get the relative exchange rate between the two currencies.
if ((0, has_key_js_1.default)(rates, from) && (0, has_key_js_1.default)(rates, to)) {
return rates[to] * (1 / rates[from]);
}
throw new Error('The `rates` object does not contain either the `from` or `to` currency.');
}
else {
throw new Error('Please specify the `from` and/or `to` currency, or use parsing.');
}
}
exports.default = getRate;