-
Notifications
You must be signed in to change notification settings - Fork 11
/
combiner.js
52 lines (50 loc) · 1.33 KB
/
combiner.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
var combine = require('stream-combiner')
var split = require('split')
var zlib = require('zlib')
var through = require('through')
module.exports = function () {
var titles_by_genre = {}
var grouper = {
genres: {},
current_genre: undefined,
on_row: function (row) {
if (row.type == 'genre') {
old_genre = this.current_genre
this.current_genre = row.name
if (this.current_genre) {
this.genres[this.current_genre] = {
name: this.current_genre,
books: []
}
}
return this.genres[old_genre]
}
if (row.type === 'book') {
this.genres[this.current_genre].books.push(row.name)
return null
}
}
}
return combine(
// can't just do split(JSON.parse) because it chokes on final empty line
split(),
through(function (text) {
if (text.length > 0) this.queue(JSON.parse(text))
}),
through(function on_write (row) {
record = grouper.on_row(row)
if (record) {
json = JSON.stringify(record)
this.queue(json)
this.queue('\n')
}
}, function on_end () {
record = grouper.on_row({type: 'genre', name: undefined})
json = JSON.stringify(record)
this.queue(json)
this.queue('\n')
this.queue(null)
}),
zlib.createGzip()
)
}