-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.js
93 lines (76 loc) · 2.2 KB
/
convert.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
86
87
88
89
90
91
92
93
'use strict'
const fs = require('fs')
const path = require('path')
const stops = require('vbb-stations/full.json')
const lines = require('vbb-lines')
const weights = require('vbb-mode-weights')
const parse = require('vbb-parse-line')
const pick = require('lodash.pick')
const sink = require('stream-sink')
const trips = require('vbb-trips')
const through = require('through2')
// link stops to stations
for (let stationId in stops) {
const station = stops[stationId]
for (let stop of station.stops)
stops[stop.id] = station
}
const computeLinesAt = (linesAt, lines) => (schedule, _, cb) => {
const line = lines.find((line) => line.id === schedule.route.line)
if (!line) {
console.error(`line ${schedule.route.line} of schedule ${schedule.id} does not exist`)
cb()
return
}
let base = weights[line.product] || .2
const parsed = parse(line.name)
if (parsed.type === 'bus' && (parsed.express || parsed.express)) base += .05
let weight = 0
for (let variant of line.variants) {
weight += base * variant.trips * variant.stops.length
}
const lineAt = {...line, weight}
for (let variant of line.variants) {
for (let stopId of variant.stops) {
const station = stops[stopId]
if (!station) {
console.error('Unknown stop', stopId, 'of line', line.id)
continue
}
if (!linesAt[station.id]) {
linesAt[station.id] = [lineAt]
} else if (!linesAt[station.id].some((l) => l.id === line.id)) {
linesAt[station.id].push(lineAt)
}
}
}
cb()
}
const writeJSON = (data, file) => new Promise((yay, nay) => {
fs.writeFile(path.join(__dirname, file), JSON.stringify(data), (err) => {
if (err) nay(err)
else yay()
})
})
lines('all')
.pipe(sink('object'))
.then((lines) => new Promise((yay, nay) => {
const linesAt = {}
trips.schedules()
.pipe(through.obj(computeLinesAt(linesAt, lines)))
.on('data', () => {})
.once('end', () => yay(linesAt))
.once('error', (err) => nay(err))
}))
.then((linesAt) => {
for (let station in linesAt) {
linesAt[station] = linesAt[station]
.sort((a, b) => b.weight - a.weight)
.map((line) => pick(line, ['type', 'id', 'name', 'mode', 'product']))
}
return writeJSON(linesAt, 'data.json')
})
.catch((err) => {
console.error(err)
process.exit(1)
})