-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
47 lines (38 loc) · 1.43 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
const countries = require('./countries.json');
const countriesObject = {};
const codesObject = {};
countries.forEach(obj => (countriesObject[obj.code] = obj.country));
countries.forEach(obj => (codesObject[obj.country] = obj.code));
// return the country name for a given code
const getCountry = code => countriesObject[code];
// return the code for a given country name
const getCode = country => codesObject[country];
// return an array or an object (with codes as keys) of all countries
function getCountries(props = {}) {
// default behaviour: object === false, extended === false
const { object, extended } = props;
let allCountries = countries;
if (!extended) allCountries = countries.filter(obj => !obj.extended);
if (object) {
const result = {};
allCountries.forEach(obj => (result[obj.code] = obj.country));
return result;
}
return allCountries.map(obj => obj.country);
}
// return an array or an object (with countries as keys) of all country codes
function getCodes(props = {}) {
const { object, extended } = props;
let allCountries = countries;
if (!extended) allCountries = countries.filter(obj => !obj.extended);
if (object) {
const result = {};
allCountries.forEach(obj => (result[obj.country] = obj.code));
return result;
}
return allCountries.map(obj => obj.code);
}
exports.getCountry = getCountry;
exports.getCode = getCode;
exports.getCountries = getCountries;
exports.getCodes = getCodes;