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 24, 2015
1 parent ffdedcd commit 1b81c4a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
13 changes: 11 additions & 2 deletions lib/Catmandu/Iterable.pm
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
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_array(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 1b81c4a

Please sign in to comment.