diff --git a/lib/Catmandu/Iterable.pm b/lib/Catmandu/Iterable.pm index 23c26aa4c..fd3644562 100644 --- a/lib/Catmandu/Iterable.pm +++ b/lib/Catmandu/Iterable.pm @@ -39,6 +39,11 @@ sub to_array { \@a; } +sub to_sorted { + my ($self, $sort) = @_; + [ sort $sort @{ $self->to_array } ] +} + sub count { my ($self) = @_; my $next = $self->generator; @@ -481,6 +486,15 @@ a second invocation. Return all the items in the Iterator as an ARRAY ref. +=head2 to_sorted( 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_sorted( 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..9e7054f8a 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_sorted(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;