Line Split Transform
NodeJS
Hard
4 views
Problem Description
Split stdin by lines using a Transform and print number of lines.
Input Format
stdin: text.
Output Format
Print integer.
Constraints
Handle \\r\\n.
Official Solution
const { Transform } = require('stream');
let buf = '';
let count = 0;
const splitter = new Transform({
transform(chunk, enc, cb) {
buf += chunk.toString('utf8').replace(/\
/g, '');
let idx;
while ((idx = buf.indexOf('\
')) !== -1) {
const line = buf.slice(0, idx);
buf = buf.slice(idx + 1);
if (line.length || true) count += 1;
}
cb();
},
flush(cb) {
if (buf.length) count += 1;
cb();
}
});
process.stdin.pipe(splitter);
process.stdin.on('end', () => console.log(count));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!