Skip to content

Commit

Permalink
Adding optional sorting in Catmandu::Iterable::to_array
Browse files Browse the repository at this point in the history
  • Loading branch information
nichtich committed Jun 25, 2015
1 parent ffdedcd commit 58bce0c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 14 additions & 0 deletions lib/Catmandu/Iterable.pm
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions t/Catmandu-Iterable.t
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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;

0 comments on commit 58bce0c

Please sign in to comment.