Circular Buffer Fixed Capacity
Implement a fixed-capacity circular buffer with O(1) push and read for streaming window statistics.
Code
export class CircularBuffer<T>{private buffer:(T|undefined)[];private head=0;private tail=0;private count=0;constructor(private capacity:number){this.buffer=new Array(capacity);}push(item:T):T|undefined{const evicted=this.isFull()?this.buffer[this.head]:undefined;this.buffer[this.tail]=item;this.tail=(this.tail+1)%this.capacity;if(this.isFull())this.head=(this.head+1)%this.capacity;else this.count++;return evicted;}read():T|undefined{if(this.isEmpty())return undefined;const item=this.buffer[this.head];this.buffer[this.head]=undefined;this.head=(this.head+1)%this.capacity;this.count--;return item;}isFull(){return this.count===this.capacity;}isEmpty(){return this.count===0;}size(){return this.count;}toArray():T[]{const result:T[]=[];for(let i=0;i<this.count;i++)result.push(this.buffer[(this.head+i)%this.capacity]as T);return result;}}How the snippet works
Count the class CircularBuffer as the entire surface area of Circular Buffer Fixed Capacity.
Applying it
The surface worth importing is CircularBuffer; the helpers around it are private to the snippet.
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.