Skip to content

Commit

Permalink
added uniq method to Mojo::Collection
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Jul 3, 2012
1 parent e2e32ce commit 497c342
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Changes
@@ -1,6 +1,6 @@

3.02 2012-07-03
- Added pluck method to Mojo::Collection.
- Added pluck and uniq methods to Mojo::Collection.
- Added regular expression support to first and grep methods in
Mojo::Collection.
- Improved documentation.
Expand Down
12 changes: 12 additions & 0 deletions lib/Mojo/Collection.pm
Expand Up @@ -77,6 +77,12 @@ sub sort {
return $self->new(sort { $a->$cb($b) } @$self);
}

sub uniq {
my $self = shift;
my %seen;
return $self->new(grep { !$seen{$_}++ } @$self);
}

1;

=head1 NAME
Expand Down Expand Up @@ -219,6 +225,12 @@ from the results.
my $insensitive = $collection->sort(sub { uc(shift) cmp uc(shift) });
=head2 C<uniq>
my $new = $collection->uniq;
Create a new collection without duplicate elements.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
Expand Down
8 changes: 7 additions & 1 deletion t/mojo/collection.t
@@ -1,6 +1,6 @@
use Mojo::Base -strict;

use Test::More tests => 55;
use Test::More tests => 57;

# "'What are you lookin at?' - the innocent words of a drunken child."
use Mojo::Collection 'c';
Expand Down Expand Up @@ -119,3 +119,9 @@ is_deeply [$collection->slice(6 .. 9)->each], [7, 10, 9, 8], 'right result';
$collection = c(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9));
is $collection->pluck('reverse'), "3\n2\n1\n6\n5\n4\n9\n8\n7", 'right result';
is $collection->pluck(join => '-'), "1-2-3\n4-5-6\n7-8-9", 'right result';

# uniq
$collection = c(1, 2, 3, 2, 3, 4, 5, 4);
is_deeply [$collection->uniq->each], [1, 2, 3, 4, 5], 'right result';
is_deeply [$collection->uniq->reverse->uniq->each], [5, 4, 3, 2, 1],
'right result';

0 comments on commit 497c342

Please sign in to comment.