-
Notifications
You must be signed in to change notification settings - Fork 468
/
Copy pathbuild-chapters.js
executable file
·69 lines (62 loc) · 1.73 KB
/
build-chapters.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
#!/usr/bin/env node
const Fs = require('fs')
const cmdwatcher = require('./util/cmdwatcher')
const mkdirp = require('mkdirp')
function groupByValue(list, grouper, groupName) {
var grouped = {}
groupName = groupName || 'items'
var listLength = list.length;
for (var i = 0; i < listLength; i++) {
var key = list[i][grouper]
if (typeof grouped[key] !== "object" || typeof grouped[key].push !== "function") {
grouped[key] = []
}
grouped[key].push(list[i])
}
return Object.keys(grouped).map(function (group) {
var formatted = {}
formatted[grouper] = group
formatted.count = grouped[group].length
formatted[groupName] = grouped[group]
return formatted
})
}
function sortByKey(list, key) {
return list.sort(function (a, b) {
return a[key] > b[key] ? 1 : 0
})
}
function sortedGroupByValue(list, grouper, groupName) {
return sortByKey(groupByValue(list, grouper, groupName), grouper)
}
var chapters = []
cmdwatcher('build-chapters'
, './chapters/!(list).json', function (files) {
files.forEach(function (f) {
Fs.readFile(f, function (err, buf) {
if (err) {
return console.error(err)
}
var data = buf.toString()
try {
var chapter = JSON.parse(data)
} catch (e) {
console.error("JSON parse error: " + f, e)
}
chapters.push(chapter)
if (chapters.length === files.length) {
writeChapters(chapters)
}
})
})
})
function writeChapters(chapters) {
data = {
total: chapters.length,
regions: sortedGroupByValue(chapters, 'region', 'chapters')
}
mkdirp.sync('.build/chapters')
Fs.writeFile('.build/chapters/list.json', JSON.stringify(data, null, 2), function (err) {
if (err) console.error(err)
})
}