-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (62 loc) · 1.72 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
60
61
62
63
64
65
66
67
68
const fs = require('fs')
const path = require('path')
const country = require('country-data')
const _ = require('lodash')
const lookup = country.lookup
const allCountries = country.countries.all
let dicts = []
const normalizedPath = path.join(__dirname, './', 'dicts')
fs.readdirSync(normalizedPath).forEach((file) => {
if (/\.dict\./.test(file)) {
let content = require(path.join(normalizedPath, file))
dicts.push(content)
}
})
const convert = (countryName) => {
let country = getCountry(countryName)
return (country || {}).alpha2 || null
}
const getCountry = (countryName) => {
let countries = lookup.countries({
name: countryName
})
// try to find country without case insensitive
if (countries.length === 0 && countryName) {
let _country = _.find(allCountries, (item) => {
if (item && item.name && item.name.toLowerCase() === countryName.toLowerCase()) {
return item.name
}
})
if (_country) {
return (_country)
}
}
// try to find country inside dicts
if (countries.length === 0 && countryName) {
const cName = findCaseInsensitive(countryName)
countries = lookup.countries({
name: cName
})
}
return countries[0] || null
}
const findCaseInsensitive = (countryName) => {
for (let i = 0; i < dicts.length; i++) {
let dict = dicts[i]
const countries = Object.keys(dict)
for (let j = 0; j < countries.length; ++j) {
const name = countries[j]
if (name === countryName || name.toLowerCase() === countryName.toLowerCase()) {
return dict[name]
}
}
}
}
const iso = (countryName) => {
let country = getCountry(countryName) || {}
return (country.name || null)
}
module.exports = {
convert: convert,
iso: iso
}