-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
85 lines (73 loc) · 2.39 KB
/
utils.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import YAML from 'yaml'
import fs from 'fs'
import _ from 'lodash'
// Read data from a YAML file.
export const readYAML = f => YAML.parse(fs.readFileSync(f).toString())
// Write JSON data to a file.
export const writeJsonData = (filename, jsonData) => {
fs.writeFileSync(filename, JSON.stringify(jsonData), 'utf-8')
console.log(`data written to '${filename}'.`)
}
export const formatDate = (rawDate) => {
const year = rawDate.getFullYear().toString()
const month = (rawDate.getMonth() + 1).toString().padStart(2, '0')
const day = rawDate.getDate().toString().padStart(2, '0')
if (year === 'NaN') {
return undefined
} else {
return `${year}-${month}-${day}`
}
}
const countryData = _.memoize(() => {
const codeToCountry = readYAML('countries.yaml')
const countryToCodeInitial = invertMap(codeToCountry)
const countryAliases = readYAML('country_aliases.yaml')
return {
codeToCountry,
countryToCode: { ...countryToCodeInitial, ...countryAliases }
}
})
export const nwfzList = _.memoize(() => {
const { nwfzTreaties } = readYAML('inputs.yaml')
return nwfzTreaties.map(t => t.code)
})
export const countryToCode = (country) => {
const { countryToCode } = countryData()
if (!countryToCode[country]) {
throw new Error(`country code for '${country}' not found.`)
}
return countryToCode[country]
}
export const codeToCountry = (code) => {
const { codeToCountry } = countryData()
if (!codeToCountry[code]) {
throw new Error(`country name for code '${code}' not found.`)
}
return codeToCountry[code]
}
export const inputs = _.memoize(() => readYAML('inputs.yaml'))
export const treatyInfoByCode = _.memoize(() => {
const results = {}
const { disarmamentTreaties, otherUNTreaties, nwfzTreaties } = inputs()
const list = [...disarmamentTreaties, ...otherUNTreaties,
...nwfzTreaties,
{ code: 'nwfz', name: 'Nuclear-Weapon-Free Zone', logo: 'nwfz.jpeg' }]
for (const item of list) {
results[item.code] = item
}
return results
})
export const invertMap = (m) => {
const result = {}
for (const [k, v] of Object.entries(m)) {
if (result[v]) {
throw new Error('Map not invertable')
}
result[v] = k
}
return result
}
export const mapParallel = (asyncFunc, items) =>
Promise.all(items.map(item => asyncFunc(item)))
export const mapParallelToObject = async (asyncFunc, items) =>
Object.fromEntries(await mapParallel(asyncFunc, items))