Skip to content

Commit fca7f41

Browse files
feat(2020-day-06): stream handler utility for generating checksums
1 parent 89b12db commit fca7f41

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

2020/day-06/streamHandler.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const fs = require('fs')
2+
const split2 = require('split2')
3+
4+
const defaultProcessor = (data) => {
5+
console.info('Data chunk:')
6+
console.debug(data)
7+
console.info('-----------')
8+
return 1
9+
}
10+
11+
const streamHandler = ({ filePath, processor = defaultProcessor }) => {
12+
let checksum = 0
13+
let buffer = ''
14+
15+
return new Promise((resolve, reject) => {
16+
return fs.createReadStream(filePath)
17+
.pipe(split2())
18+
.on('data', (data) => {
19+
// Emmpty line indicates record separator
20+
if (data.trim() === '') {
21+
checksum += processor(buffer)
22+
// flush buffer
23+
buffer = ''
24+
return
25+
}
26+
// Add the line to the buffer
27+
buffer += data.trim() + '\n'
28+
})
29+
.on('end', (data) => {
30+
// get the final record from the buffer
31+
checksum += processor(buffer)
32+
console.debug('Finished stream. Checksum:', checksum)
33+
resolve({ checksum })
34+
})
35+
.on('error', reject)
36+
})
37+
}
38+
39+
module.exports = {
40+
streamHandler
41+
}

2020/day-06/streamHandler.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* eslint-env mocha */
2+
const { expect } = require('chai')
3+
const path = require('path')
4+
// const { groupChecksum } = require('./questions')
5+
const { streamHandler } = require('./streamHandler')
6+
7+
const filePath = path.join(__dirname, 'testData.txt')
8+
9+
describe('--- Day 6: Custom Customs ---', () => {
10+
describe('Part 1', () => {
11+
describe('streamHandler()', () => {
12+
it('parses a stream processing a running checksum', (done) => {
13+
streamHandler({ filePath })
14+
.then(({ checksum }) => {
15+
expect(checksum).to.equal(5)
16+
done()
17+
})
18+
})
19+
it('accepts a custom function to calculate checksums', (done) => {
20+
const processor = () => { return 2 }
21+
streamHandler({ filePath, processor })
22+
.then(({ checksum }) => {
23+
expect(checksum).to.equal(5 * 2)
24+
done()
25+
})
26+
})
27+
})
28+
})
29+
})

2020/day-06/testData.txt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
abc
2+
3+
a
4+
b
5+
c
6+
7+
ab
8+
ac
9+
10+
a
11+
a
12+
a
13+
a
14+
15+
b

0 commit comments

Comments
 (0)