Readable Stream Line Counter
NodeJS
Hard
3 views
Problem Description
Count how many lines are in stdin using streams.
Input Format
stdin: text.
Output Format
Print integer lines.
Constraints
Handle last line without newline.
Official Solution
let count = 0;
let lastWasNewline = false;
process.stdin.on('data', (chunk) => {
for (const b of chunk) {
if (b === 10) {
count += 1;
lastWasNewline = true;
} else {
lastWasNewline = false;
}
}
});
process.stdin.on('end', () => {
const inputHadData = count > 0 || !lastWasNewline;
if (!inputHadData) return;
if (!lastWasNewline) count += 1;
console.log(count);
});
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!