Circular Buffer CLI
A Node CLI that implements a fixed-size circular buffer, accepting push and pop commands from stdin and printing the buffer state after each operation.
Project
node-circular-buffer-cli
Entry point: cbuf.mjs
Install
node --versionRun
echo "push 1\npush 2\npop\npush 3" | node cbuf.mjs 3Test
node --test cbuf.test.mjsExpected output
Prints the buffer contents after each push or pop command, showing the circular buffer state as elements wrap around.Dependencies
- node >=20
What it does
Creates a fixed-size circular buffer from the capacity argument, reads push and pop commands from stdin, and prints the buffer contents after each operation. The buffer wraps around using modular arithmetic so the head and tail pointers cycle through the array.
const cap = +process.argv[2];
const buf = new Array(cap).fill(null);
let head = 0, size = 0;
const push = v => { if (size === cap) return; buf[(head + size) % cap] = v; size++; };
const pop = () => { if (size === 0) return; const v = buf[head]; buf[head] = null; head = (head + 1) % cap; size--; return v; };
for await (const line of console) { /* stub */ }
// Real stdin loop:
const rl = require('readline').createInterface({ input: process.stdin });
rl.on('line', cmd => {
const [op, val] = cmd.split(' ');
if (op === 'push') push(+val); else if (op === 'pop') pop();
console.log(buf.slice(head, head + size).map((_, i) => buf[(head + i) % cap]).join(','));
});
Run and verify
printf "push 1\npush 2\npop\npush 3" | node cbuf.mjs 3
Run the test command to check the implementation: node --test cbuf.test.mjs.
Expected Output
For a capacity-3 buffer with the commands push 1, push 2, pop, push 3:
1
1,2
2
2,3
Limitations
A push on a full buffer is silently ignored; a pop on an empty buffer returns undefined. The buffer state is printed as a comma-separated list of live elements.