From: Ricardo Signes Date: Fri, 23 Apr 2010 20:34:17 +0000 (-0400) Subject: implement each_n_values for Indexed X-Git-Tag: 0.11~4 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=f089b8562e348fcac1d2800545e88a69d484811f;p=gitmo%2FMoose-Autobox.git implement each_n_values for Indexed --- diff --git a/lib/Moose/Autobox/Hash.pm b/lib/Moose/Autobox/Hash.pm index ed23052..ddf8c63 100644 --- a/lib/Moose/Autobox/Hash.pm +++ b/lib/Moose/Autobox/Hash.pm @@ -81,6 +81,18 @@ sub each_value { $sub->($_) for CORE::values %$hash; } +sub each_n_values { + my ($hash, $n, $sub) = @_; + my @keys = CORE::keys %$hash; + my $it = List::MoreUtils::natatime($n, @keys); + + while (my @vals = $it->()) { + $sub->(@$hash{ @vals }); + } + + return; +} + # End Indexed diff --git a/lib/Moose/Autobox/Indexed.pm b/lib/Moose/Autobox/Indexed.pm index 26a4893..3c80830 100644 --- a/lib/Moose/Autobox/Indexed.pm +++ b/lib/Moose/Autobox/Indexed.pm @@ -10,7 +10,7 @@ requires 'keys'; requires 'values'; requires 'kv'; requires 'slice'; -requires qw(each each_key each_value); +requires qw(each each_key each_value each_n_values); 1; diff --git a/t/011_each_n_values.t b/t/011_each_n_values.t index 4f9dc29..15aeb43 100644 --- a/t/011_each_n_values.t +++ b/t/011_each_n_values.t @@ -26,4 +26,28 @@ use Moose::Autobox; } } +{ + my %hash = (a => 1, b => 2, c => 3, d => 4); + + my $href = { %hash }; + + { + my @vals; + %hash->each_n_values(2, sub { push @vals, [@_] }); + my %seen; + is(@vals, 2); + for my $pair (@vals) { $seen{$_}++ for @$pair } + is_deeply(\%seen, { 1,1,2,1,3,1,4,1 }); + } + + { + my @vals; + $href->each_n_values(2, sub { push @vals, [@_] }); + my %seen; + is(@vals, 2); + for my $pair (@vals) { $seen{$_}++ for @$pair } + is_deeply(\%seen, { 1,1,2,1,3,1,4,1 }); + } +} + done_testing;