← Runnable Projects

阅读中文版本

Windowed Counter CLI

A Node CLI that maintains a sliding-window counter over a stream of events from stdin, printing the count in the window after each event.

beginnerjavascriptunverified

Project

node-windowed-counter-cli

Entry point: wcount.mjs

Install

node --version

Run

printf "1\n2\n3\n4\n5" | node wcount.mjs 3

Test

node --test wcount.test.mjs

Expected output

Prints the count of events in the sliding window after each event, where the window size is given as an argument.

Dependencies

  • node >=20

What it does

Maintains a sliding window of the last w events from stdin. Each event is added to the window and the running count; when the window exceeds the size, the oldest event is subtracted and removed. The count is printed after each event.

const w = +process.argv[2];
const buf = [];
let count = 0;
const rl = require('readline').createInterface({ input: process.stdin });
rl.on('line', line => {
  const val = +line;
  buf.push(val);
  count += val;
  if (buf.length > w) count -= buf.shift();
  console.log(count);
});

Run and verify

printf "1\n2\n3\n4\n5" | node wcount.mjs 3

Run the test command to check the implementation: node --test wcount.test.mjs.

Expected Output

With a window of 3, the counts are 1, 3, 6, 9, 12 as the window slides:

1
3
6
9
12

Limitations

The window is count-based (last N events), not time-based. A time-based window would need timestamps and a different eviction strategy. The buffer stores every event, so memory is O(w).