Permalink
Browse files

implement inatatime: return n elements at a time from an interable value

  • Loading branch information...
1 parent e4f18f5 commit 8e913f481deafc1965e7f02bc8b5ba1eb17107cd @pcmantz pcmantz committed Dec 28, 2011
Showing with 26 additions and 2 deletions.
  1. +18 −0 lib/Iterator/Simple/Util.pm
  2. +8 −2 t/iterator-simple-util.t
@@ -9,6 +9,7 @@ use Sub::Exporter -setup => {
iany inone inotall
ifirstval ilastval
ibefore ibefore_incl iafter iafter_incl
+ inatatime
)
]
};
@@ -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;
View
@@ -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 )
);
}
@@ -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 8e913f4

Please sign in to comment.