-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
59 lines (53 loc) · 1.54 KB
/
index.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
55
56
57
58
59
'use strict';
const map = require('./data/iso-4217.json');
const countryCurrencies = require('./data/iso-3166-1-alpha-2-to-iso-4217.json');
const codes = Object.keys(map);
const currencies = codes.map(code => map[code]);
class CurrencyNotFoundError extends Error {
constructor(currencyCode) {
const message = currencyCode ?
`currency '${currencyCode}' not found` :
`currency not found`;
super(message);
this.name = 'CurrencyNotFoundError';
this.code = currencyCode || '';
}
}
class CountryCurrencyNotFoundError extends Error {
constructor(country) {
country = country || '';
const message = `currency for country '${country}' not found`;
super(message);
this.name = 'CountryCurrencyNotFoundError';
this.country = country;
}
}
const lib = {
CountryCurrencyNotFoundError,
CurrencyNotFoundError,
codes,
currencies,
map,
guessCodeForCountry: function (countryCode) {
const code = codes.find(code => 0 === code.indexOf(countryCode));
if (!code) {
throw new CountryCurrencyNotFoundError(countryCode);
}
return code;
},
codeForCountry: function(countryCode) {
const currencyCode = countryCurrencies[countryCode];
return currencyCode ? currencyCode : lib.guessCodeForCountry(countryCode);
},
country: function(countryCode) {
return lib.currency(lib.codeForCountry(countryCode));
},
currency: function(currency) {
const meta = map[currency];
if (!meta) {
throw new CurrencyNotFoundError(currency);
}
return meta;
},
};
module.exports = lib;