Circular Buffers
Drift Common provides circular buffer implementations for efficient, fixed-size data storage with automatic overflow handling.Available Classes
- CircularBuffer - Basic circular buffer with FIFO behavior
- UniqueCircularBuffer - Circular buffer that enforces element uniqueness
CircularBuffer
A basic circular buffer implementation that stores elements in a fixed-size buffer. When the buffer is full, adding a new element removes the oldest element.Import
Constructor
capacity- Maximum number of elements the buffer can hold
Properties
Methods
add(value: T): T | null
Adds a value to the buffer. Returns the removed value if the buffer was full, or null otherwise.toArray(): T[]
Returns all elements in the buffer as an array, starting from the oldest element.Usage Examples
Price History Buffer
Recent Events Log
Moving Average Calculator
UniqueCircularBuffer
A circular buffer that only allows unique elements based on a key generator function. Attempting to add a duplicate element will be rejected.Import
Constructor
capacity- Maximum number of elementsuniquenessKeyGenerator- Function that generates a unique key for each element
Properties
Inherits all properties from CircularBuffer:Methods
add(value: T): boolean
Tries to add an element to the buffer. Returns true if the element was added, false if it was a duplicate.toArray(): T[]
Returns all unique elements in the buffer as an array.Usage Examples
Recent Transaction Tracker
Unique User Activity Log
Unique Market Price Updates
Choosing Between Buffer Types
Use CircularBuffer when:
- You need simple FIFO behavior
- Duplicates are allowed or expected
- Performance is critical (no uniqueness checking)
- You’re storing time-series data
- Price history
- Event logs
- Performance metrics
- Moving averages
Use UniqueCircularBuffer when:
- Each element must be unique
- You want to prevent duplicate processing
- You’re tracking distinct items
- Memory efficiency for unique items is important
- Transaction signatures
- User activities (deduplicated)
- Unique market updates
- Recent search queries (deduplicated)
Performance Considerations
CircularBuffer
- add(): O(1) - Constant time insertion
- toArray(): O(n) - Linear time array creation
- Memory: Fixed size, no overhead
UniqueCircularBuffer
- add(): O(1) - Constant time with Set lookup
- toArray(): O(n) - Linear time array creation
- Memory: Fixed buffer size + Set for tracking unique keys
Best Practices
Choose Appropriate Capacity
Use Efficient Key Generators
Handle Capacity Carefully
Related
- COMMON_UTILS - Additional utility functions
- Math Utilities - Math operations for buffer data