-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (45 loc) · 1.02 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
const Transform = require('stream').Transform;
class WordCount extends Transform {
constructor() {
super({ readableObjectMode: true });
this._chars = 1;
this._lines = 1;
this._words = 0;
}
_transform(chunk, encoding, callback) {
const data = chunk.toString();
this._countChars(data);
this._countLines(data);
this._countWords(data);
callback();
}
_flush(callback) {
this.push({ word: this._words, line: this._lines, char: this._chars });
callback();
}
_countChars(data) {
this._chars += data.length;
}
_countLines(data) {
for (let char of data) {
if (char === '\n')
this._lines++;
}
}
_countWords(data) {
let inWord = false;
let isWhitespace = (c) => { return c === ' ' || c === '\n' }
for (let char of data) {
if (!isWhitespace(char)) {
if (!inWord)
this._words++;
inWord = true;
} else {
inWord = false;
}
}
}
}
module.exports = function () {
return new WordCount();
}