Iterator-Flex

 view release on metacpan or  search on metacpan

lib/Iterator/Flex/Cycle.pm  view on Meta::CPAN

package Iterator::Flex::Cycle;

# ABSTRACT: Array Cycle Iterator Class

use v5.28;
use strict;
use warnings;
use experimental 'signatures';

our $VERSION = '0.34';

use Iterator::Flex::Utils ':IterAttrs', 'throw_failure';
use Ref::Util;
use namespace::clean;

use parent 'Iterator::Flex::Base';




























sub new ( $class, $array, $ ) {

    throw_failure( parameter => q{argument must be an ARRAY reference} )
      unless Ref::Util::is_arrayref( $array );

    $class->SUPER::new( { array => $array }, {} );
}

sub construct ( $class, $state ) {

    throw_failure( parameter => q{state must be a HASH reference} )
      unless Ref::Util::is_hashref( $state );

    my ( $arr, $prev, $current, $next )
      = @{$state}{qw[ array prev current next ]};

    my $len = @$arr;

    $next = 0 unless defined $next;

    throw_failure( parameter => q{illegal value for 'prev'} )
      if defined $prev && ( $prev < 0 || $prev >= $len );

    throw_failure( parameter => q{illegal value for 'current'} )
      if defined $current && ( $current < 0 || $current >= $len );

    throw_failure( parameter => q{illegal value for 'next'} )
      if $next < 0 || $next > $len;


    return {

        ( +RESET ) => sub {
            $prev = $current = undef;
            $next = 0;
        },

        ( +REWIND ) => sub {
            $next = 0;
        },

        ( +PREV ) => sub {
            return defined $prev ? $arr->[$prev] : undef;
        },

        ( +CURRENT ) => sub {
            return defined $current ? $arr->[$current] : undef;
        },

        ( +NEXT ) => sub {
            $next    = 0 if $next == $len;
            $prev    = $current;
            $current = $next++;
            return $arr->[$current];
        },

        ( +FREEZE ) => sub {
            return [
                $class,
                {
                    array   => $arr,
                    prev    => $prev,
                    current => $current,
                    next    => $next,
                },
            ];
        },
    };
}


__PACKAGE__->_add_roles( qw[



( run in 0.910 second using v1.01-cache-2.11-cpan-6aa56a78535 )