-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathOpenExchangeRates.js
54 lines (53 loc) · 1.64 KB
/
OpenExchangeRates.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var OpenExchangeRates = function () {
/*! (c) Andrea Giammarchi */
return function OpenExchangeRates(APP_ID) {
var cache = {};
return {
format: (amount, currency) =>
format(amount, currency),
clear: (base) =>
delete cache[(base || 'USD').toUpperCase()],
convert: (amount, from, to) =>
latest(from).then(info =>
format(info.rates[to.toUpperCase()] * amount, to)),
currencies: () =>
cache.currencies || (cache.currencies = new Promise((res, rej) => {
load(urlFor('currencies'), res, rej);
})),
latest: (base) => {
base = (base || 'USD').toUpperCase();
return cache[base] || (cache[base] = new Promise((res, rej) => {
load(`${urlFor('latest')}&base=${base}`, res, rej);
}));
}
};
function urlFor(key) {
return `https://openexchangerates.org/api/${key}.json?app_id=${APP_ID}`;
}
function latest(base) {
base = (base || 'USD').toUpperCase();
return cache[base] || (cache[base] = new Promise((res, rej) => {
load(`${urlFor('latest')}&base=${base}`, res, rej);
}));
}
};
function format(amount, currency) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency,
minimumFractionDigits: 2,
maximumFractionDigits: 8
})
.format(amount)
.replace(/^NaN$/, '')
.replace(/^(\D+)/, '$1 ')
.replace('BTC', '₿');
}
function load(url, res, rej) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onload = () => res(JSON.parse(xhr.responseText));
xhr.onerror = rej;
xhr.send(null);
}
}();