Skip to content

Commit

Permalink
sort method to Mojo::Collection can use $a,$b
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Henning Thorsen committed Aug 5, 2014
1 parent 556a858 commit f2e2e4f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/Mojo/Collection.pm
Expand Up @@ -92,7 +92,17 @@ sub slice {

sub sort {
my ($self, $cb) = @_;
return $self->new($cb ? sort { $a->$cb($b) } @$self : sort @$self);

return $self->new(sort @$self) unless $cb;

my $caller = caller;
no strict 'refs';
return $self->new(
sort {
local (*{"$caller\::a"}, *{"$caller\::b"}) = (\$a, \$b);
$a->$cb($b);
} @$self
);
}

sub tap { shift->Mojo::Base::tap(@_) }
Expand Down Expand Up @@ -299,7 +309,7 @@ Number of elements in collection.
Sort elements based on return value of callback and create a new collection
from the results.
my $insensitive = $collection->sort(sub { uc(shift) cmp uc(shift) });
my $insensitive = $collection->sort(sub { uc($a) cmp uc($b) });
=head2 tap
Expand Down
2 changes: 2 additions & 0 deletions t/mojo/collection.t
Expand Up @@ -121,6 +121,8 @@ is c()->reduce(sub { $a + $b }), undef, 'no result';
# sort
$collection = c(2, 5, 4, 1);
is_deeply [$collection->sort->each], [1, 2, 4, 5], 'right order';
is_deeply [$collection->sort(sub { $b cmp $a })->each], [5, 4, 2, 1],
'right order';
is_deeply [$collection->sort(sub { $_[1] cmp $_[0] })->each], [5, 4, 2, 1],
'right order';
$collection = c(qw(Test perl Mojo));
Expand Down

0 comments on commit f2e2e4f

Please sign in to comment.