Hax-Alg-RollingWindow

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN

[![CI](https://github.com/haxmeister/Hax-Alg-RollingWindow/actions/workflows/ci.yml/badge.svg)](https://github.com/haxmeister/Hax-Alg-RollingWindow/actions/workflows/ci.yml)

# Hax::Alg::RollingWindow

A **fixed-capacity rolling window** (overwrite-oldest) implemented with an **array-backed circular buffer**.

When the window is full and you add new items, the **oldest** items are automatically evicted. This is designed for streaming, metrics, logging, and sliding-window workloads where you want to keep only the most recent *N* values.

## Features

- O(1) insertion (`add`) per element
- O(1) random access (`get`)
- O(n) snapshot (`values`)
- Handles **any Perl scalar**: numbers, strings, refs, objects
- Evicted / cleared slots are set to `undef` so references are released promptly
- Minimal method call overhead and predictable behavior

## Install

### From CPAN
```sh
cpanm Hax::Alg::RollingWindow
```

### From source (this repository)
```sh
perl Makefile.PL
make
make test
make install
```

## Quick start

```perl
use Hax::Alg::RollingWindow;

my $w = Hax::Alg::RollingWindow->new(capacity => 5);

$w->add(1, 2, 3);
$w->add(4, 5);

my @vals = $w->values;  # (1, 2, 3, 4, 5)

$w->add(6);             # evicts 1
@vals = $w->values;     # (2, 3, 4, 5, 6)

print "oldest=", $w->oldest, " newest=", $w->newest, "\n";
```

## Eviction callback (`on_evict`)

You may provide an optional callback that receives each evicted element:

```perl
my @evicted;

my $w = Hax::Alg::RollingWindow->new(
    capacity => 3,
    on_evict => sub {
        my ($old) = @_;
        push @evicted, $old;
    },
);

$w->add(qw(a b c d e));   # evicts a, then b
# @evicted = ('a', 'b')



( run in 0.768 second using v1.01-cache-2.11-cpan-140bd7fdf52 )