From: Florian Ragwitz Date: Mon, 1 Feb 2010 02:52:18 +0000 (+0100) Subject: Add Array->each_n. X-Git-Tag: 0.11~7 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=0e4809110e25a83f84e51bd913ae9e233fb3ce63;p=gitmo%2FMoose-Autobox.git Add Array->each_n. --- diff --git a/Makefile.PL b/Makefile.PL index e14ec21..cde3758 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -10,7 +10,7 @@ requires 'autobox' => '2.23'; requires 'Moose' => '0.42'; requires 'Perl6::Junction' => '1.40000'; -test_requires 'Test::More' => '0.62'; +test_requires 'Test::More' => '0.89'; test_requires 'Test::Exception' => '0.21'; auto_manifest; diff --git a/lib/Moose/Autobox/Array.pm b/lib/Moose/Autobox/Array.pm index e43c893..ab28fbf 100644 --- a/lib/Moose/Autobox/Array.pm +++ b/lib/Moose/Autobox/Array.pm @@ -134,6 +134,17 @@ sub each_value { $sub->($_) for @$array; } +sub each_n { + my ($array, $n, $sub) = @_; + my $it = List::MoreUtils::natatime($n, @$array); + + while (my @vals = $it->()) { + $sub->(@vals); + } + + return; +} + # end indexed sub flatten { @@ -235,6 +246,8 @@ This is a role to describe operations on the Array type. =item B +=item B + =back =head2 Indexed implementation diff --git a/t/011_each_n.t b/t/011_each_n.t new file mode 100644 index 0000000..396f446 --- /dev/null +++ b/t/011_each_n.t @@ -0,0 +1,29 @@ +use strict; +use warnings; +use Test::More; + +use Moose::Autobox; + +{ + my @array = ('a' .. 'z'); + + my $aref = [ @array ]; + + { + my @vals; + @array->each_n(2, sub { push @vals, [@_] }); + is(scalar @vals, 13); + is(scalar @$_, 2) for @vals; + is_deeply(@vals->map(sub { @{ $_ } }), [@array]); + } + + { + my @vals; + $aref->each_n(2, sub { push @vals, [@_] }); + is(scalar @vals, 13); + is(scalar @$_, 2) for @vals; + is_deeply(@vals->map(sub { @{ $_ } }), $aref); + } +} + +done_testing;