CircularBuffer provides a general-purpose circular buffer data structure.
# Create a new circular buffer that holds 5 elements
iex> cb = CircularBuffer.new(5)
#CircularBuffer<[]>
# Fill it up
iex> cb = Enum.into(1..5, cb)
#CircularBuffer<[1, 2, 3, 4, 5]>
# Verify that 1 is the oldest and 5 is the newest element in the buffer
iex> CircularBuffer.oldest(cb)
1
iex> CircularBuffer.newest(cb)
5
# Add another element. 1 gets pushed out.
iex> cb = CircularBuffer.insert(cb, 6)
#CircularBuffer<[2, 3, 4, 5, 6]>
# CircularBuffer implements Enumerable so all Enum.* functions work
iex> Enum.sum(cb)
20
def deps do
[
{:circular_buffer, "~> 1.0"}
]
end
The entire codebase consists of around 70 lines, has been property-tested, and
has been in production for several years. Its implementation is similar to
Erlang’s queue
module
but simplified for the circular buffer use case.