UNPKG

2.53 kBJavaScriptView Raw
1var read = require('fs').readFileSync
2var gunzip = require('zlib-browserify').gunzipSync
3var join = require('path').join
4
5var countries = read(join(__dirname, '../data', '/countries.json.gz'))
6var ISOCodes = JSON.parse(gunzip(countries).toString())
7
8module.exports = (function iso3166() {
9 var state = ''
10
11 /**
12 * Convert an ISO 3166-1 alpha-3 code to alpha-2
13 *
14 * @param {String} alpha3 USA
15 * @return {String}
16 */
17 var to2 = function to2(alpha3) {
18 if (alpha3 && alpha3.length > 1) state = alpha3
19 if (state.length !== 3) return state
20 return ISOCodes.filter(function(row) {
21 return row.alpha3 === state
22 })[0].alpha2
23 }
24
25 /**
26 * Convert an ISO 3166-1 alpha-2 code to alpha-3
27 *
28 * @param {String} alpha2 US
29 * @return {String}
30 */
31 var to3 = function to3(alpha2) {
32 if (alpha2 && alpha2.length > 1) state = alpha2
33 if (state.length !== 2) return state
34 return ISOCodes.filter(function(row) {
35 return row.alpha2 === state
36 })[0].alpha3
37 }
38
39 /**
40 * Prepare an ISO 3166-1 alpha-2 or alpha-3 code
41 * for conversion.
42 *
43 * @param {String} code USA
44 * @return {Function}
45 */
46 var from = function from(code) {
47 if (typeof code !== 'string') return state
48 state = code.toUpperCase()
49 return this
50 }
51
52 /**
53 * Prepare an ISO 3166-1 alpha-2 and ISO 639-1 pair
54 * for conversion.
55 *
56 * @param {String} locale en-US
57 * @return {Function}
58 */
59 var fromLocale = function fromLocale(locale) {
60 if (typeof locale !== 'string') return state
61 state = locale.split('-').pop().toUpperCase()
62 return this
63 }
64
65 /**
66 * Return an Object containing key/val pair of
67 * ISO 3166-1 alpha-2 and alpha-3 codes.
68 *
69 * @return {Object}
70 */
71 var list = function list() {
72 return ISOCodes
73 }
74
75 /**
76 * Return true if input is a known ISO 3166-1 alpha-2
77 * code, false otherwise.
78 *
79 * @param {String} alpha2
80 * @return {Boolean}
81 */
82 var is2 = function is2(alpha2) {
83 return ISOCodes.some(function(row) {
84 return row.alpha2 === alpha2
85 })
86 }
87
88 /**
89 * Return true if input is a known ISO 3166-1 alpha-3
90 * code, false otherwise.
91 *
92 * @param {String} alpha3
93 * @return {Boolean}
94 */
95 var is3 = function is3(alpha3) {
96 return ISOCodes.some(function(row) {
97 return row.alpha3 === alpha3
98 })
99 }
100
101 return {
102 to2: to2,
103 to3: to3,
104 from: from,
105 fromLocale: fromLocale,
106 list: list,
107 is2: is2,
108 is3: is3
109 }
110})()