From 1b81c4ae380b67af6bbbb925fb9e1a82f9663082 Mon Sep 17 00:00:00 2001 From: Jakob Voss Date: Wed, 24 Jun 2015 21:46:51 +0200 Subject: [PATCH] Adding optional sorting in Catmandu::Iterable::to_array --- lib/Catmandu/Iterable.pm | 13 +++++++++++-- t/Catmandu-Iterable.t | 4 ++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/Catmandu/Iterable.pm b/lib/Catmandu/Iterable.pm index 23c26aa4c..33e2917b6 100644 --- a/lib/Catmandu/Iterable.pm +++ b/lib/Catmandu/Iterable.pm @@ -29,14 +29,14 @@ requires 'generator'; } sub to_array { - my ($self) = @_; + my ($self, $sort) = @_; my $next = $self->generator; my @a; my $data; while (defined($data = $next->())) { push @a, $data; } - \@a; + $sort ? [ sort $sort @a ] : \@a; } sub count { @@ -481,6 +481,15 @@ a second invocation. Return all the items in the Iterator as an ARRAY ref. +=head2 to_array( CODE ) + +Return all the items in the Iterator as a sorted ARRAY ref. The sort routine is passed to +items to compare with return value C<-1>, C<0>, or C<1>. The following are equivalent: + + [ sort { $a cmp $b } @{ $importer->to_array } ] + + $importer->to_array( sub { $_[0] cmp $_[1] } ) + =head2 count Return the count of all the items in the Iterator. diff --git a/t/Catmandu-Iterable.t b/t/Catmandu-Iterable.t index 498802c73..f5fcdc63c 100644 --- a/t/Catmandu-Iterable.t +++ b/t/Catmandu-Iterable.t @@ -44,6 +44,7 @@ throws_ok { Role::Tiny->apply_role_to_package('T::IterableWithoutGenerator', $pk my $iter = T::Iterable->new(data => [1,2,3]); is_deeply $iter->to_array, [1,2,3]; +is_deeply $iter->to_array(sub { $_[1] <=> $_[0] }), [3,2,1]; is $iter->count, 3; @@ -171,5 +172,4 @@ is_deeply $iter->stop_if(sub { shift->{n} == 1 })->to_array, is_deeply $iter->next, {n=>1}; } -done_testing 63; - +done_testing;