-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (78 loc) · 2.46 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict'
const {createReadStream, createWriteStream} = require('fs')
const {parse} = require('csv-parse');
const {Transform, PassThrough } = require('stream');
const rs = createReadStream('./london_crime_by_lsoa.csv', {highWaterMark: 64})
const ws = createWriteStream('./output.txt')
const csvParser = parse({ skip_records_with_error: true, columns: true });
const crimesPerYear = {}
const crimesPerLocation = {}
// Did the number of crimes go up or down over the years?
const firstAnswer = (crimes) => {
ws.write(`1. Did the number of crimes go up or down over the years?\n`)
const orderedByYear = Object.keys(crimes).sort().reduce((obj, key) => {
obj[key] = crimes[key]
return obj
}, {})
if(Object.values(orderedByYear) === Object.values(orderedByYear).sort()) {
ws.write('Yes\n')
} else {
ws.write('No\n')
}
}
// What are the most dangerous areas of London?
const secondAnswer = (crimes) => {
ws.write(`2. What are the most dangerous areas of London?\n`)
const sorted = Object.keys(crimes).sort(function(a,b){return crimes[a]-crimes[b]})
const mostDangerouesArea = sorted.slice(-1)[0]
ws.write(mostDangerouesArea + '\n')
}
const input = rs.pipe(csvParser)
input.pipe(new Transform({
objectMode: true,
transform(chunk, enc, cb) {
const val = chunk['year']
this.push(val)
cb()
},
})).pipe(new PassThrough({
objectMode: true,
transform(chunk, enc, cb) {
if(crimesPerYear[chunk] == undefined) {
crimesPerYear[chunk] = 0
} else {
crimesPerYear[chunk] = crimesPerYear[chunk] + 1
}
// this.push(chunk)
cb()
},
flush(cb) {
firstAnswer(crimesPerYear)
cb()
}
}))
input.pipe(new Transform({
objectMode: true,
transform(chunk, enc, cb) {
const val = chunk['borough']
this.push(val)
cb()
},
})).pipe(new PassThrough({
objectMode: true,
transform(chunk, enc, cb) {
if(crimesPerLocation[chunk] == undefined) {
crimesPerLocation[chunk] = 0
} else {
crimesPerLocation[chunk] = crimesPerLocation[chunk] + 1
}
cb()
},
flush(cb) {
secondAnswer(crimesPerLocation)
cb()
}
}))
// TODO
// What is the least common crime?
// What is the most common crime per area?