Skip to content

Commit

Permalink
Merge pull request #1 from pcmantz/inatatime
Browse files Browse the repository at this point in the history
implement inatatime: return n elements at a time from an interable value
  • Loading branch information
ray1729 committed Feb 2, 2012
2 parents e4f18f5 + 8e913f4 commit b3b6f70
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
18 changes: 18 additions & 0 deletions lib/Iterator/Simple/Util.pm
Expand Up @@ -9,6 +9,7 @@ use Sub::Exporter -setup => {
iany inone inotall
ifirstval ilastval
ibefore ibefore_incl iafter iafter_incl
inatatime
)
]
};
Expand Down Expand Up @@ -308,6 +309,23 @@ sub iafter_incl (&$) {
return ichain iter( [$_] ), $iter;
}

sub inatatime ($;$) {
my ($kicks, $iter) = @_;

$iter = iter $iter;

return iterator {
my @vals;

for (1 .. $kicks) {
my $val = $iter->next;
last unless defined $val;
push @vals, $val;
}
return @vals ? \@vals : undef;
};
}

sub _ensure_coderef {
unless( ref( shift ) eq 'CODE' ) {
require Carp;
Expand Down
10 changes: 8 additions & 2 deletions t/iterator-simple-util.t
Expand Up @@ -13,7 +13,8 @@ BEGIN {
imax imin imaxstr iminstr imax_by imin_by imaxstr_by iminstr_by
iany inone inotall
ifirstval ilastval
ibefore ibefore_incl iafter iafter_incl )
ibefore ibefore_incl iafter iafter_incl
inatatime )
);
}

Expand Down Expand Up @@ -193,6 +194,11 @@ note "Testing iafter_incl";
is_deeply $it->to_array, [3..10];
}

note "Testing inatatime";
{
ok my $it = inatatime 3, iter [0..10];
isa_ok $it, Iterator::Simple->ITERATOR_CLASS;
is_deeply $it->to_array, [ [0..2], [3..5], [6..8], [9,10] ];
}


done_testing();

0 comments on commit b3b6f70

Please sign in to comment.