This repository was archived by the owner on Jun 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
68 lines (50 loc) · 1.66 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
'use strict'
const path = require('path')
const fs = require('fs')
const ndjson = require('ndjson')
const filterStream = require('stream-filter')
const sink = require('stream-sink')
const base = path.join(__dirname, 'data')
const pass = _ => true
const filterById = (id) => (data) =>
!!(data && ('object' === typeof data) && data.id === id)
const filterByKeys = (pattern) => (data) => {
if (!data || 'object' !== typeof data) return false
for (let key in pattern) {
if (!data.hasOwnProperty(key)) return false
if (data[key] !== pattern[key]) return false
}
return true
}
const matcher = (pattern) =>
( pattern === 'all' ? pass
: ('object' === typeof pattern ? filterByKeys(pattern)
: filterById(pattern)))
const reader = (file) => function (/* promised, filter */) {
const args = Array.prototype.slice.call(arguments)
let filter = args.pop()
let promised = !!args.shift()
filter = filterStream(matcher(filter))
const reader = fs.createReadStream(path.join(base, file))
const parser = ndjson.parse()
reader.pipe(parser).pipe(filter)
if (!promised) return filter
else return new Promise((resolve, reject) => {
reader.on('error', reject)
parser.on('error', reject)
filter.on('error', reject)
const results = sink({objectMode: true})
filter.pipe(results)
results.on('error', reject)
results.on('data', resolve)
})
}
module.exports = {
_: {pass, filterById, filterByKeys, matcher, reader},
agencies: reader('agencies.ndjson'),
lines: reader('lines.ndjson'),
stations: reader('stations.ndjson'),
transfers: reader('transfers.ndjson'),
trips: reader('trips.ndjson'),
schedules: reader('schedules.ndjson')
}