Skip to content

Commit

Permalink
added reduce method to Mojo::Collection
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Dec 15, 2013
1 parent d49eb9e commit 0cc2f52
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Changes
@@ -1,5 +1,6 @@

4.61 2013-12-13
4.61 2013-12-15
- Added reduce method to Mojo::Collection.

4.60 2013-12-11
- Improved Mojolicious::Validator::Validation to allow custom validation
Expand Down
13 changes: 13 additions & 0 deletions lib/Mojo/Collection.pm
Expand Up @@ -70,6 +70,11 @@ sub pluck {
return $self->map(sub { $_->$method(@args) });
}

sub reduce {
my ($self, $cb) = @_;
return Mojo::ByteStream->new(List::Util::reduce { $a->$cb($b) } @$self);
}

sub reverse { $_[0]->new(reverse @{$_[0]}) }

sub shuffle { $_[0]->new(List::Util::shuffle @{$_[0]}) }
Expand Down Expand Up @@ -237,6 +242,14 @@ results.
# Equal to but more convenient than
my $new = $collection->map(sub { $_->$method(@args) });
=head2 reduce
my $stream = $collection->reduce(sub {...});
Reduce collection to L<Mojo::ByteStream>.
my $sum = $collection->reduce(sub { shift() + shift() });
=head2 reverse
my $new = $collection->reverse;
Expand Down
5 changes: 5 additions & 0 deletions t/mojo/collection.t
Expand Up @@ -80,6 +80,11 @@ is_deeply [@$collection], [1, 2, 3], 'right elements';
is $collection->map(sub { shift() + 2 })->join(''), '345', 'right result';
is_deeply [@$collection], [1, 2, 3], 'right elements';

# reduce
$collection = c(1, 2, 3);
is $collection->reduce(sub { shift() + shift() }), 6, 'right result';
is $collection->reduce(sub { $_[1] . $_[0] })->quote, '"321"', 'right result';

# reverse
$collection = c(3, 2, 1);
is_deeply [$collection->reverse->each], [1, 2, 3], 'right order';
Expand Down

0 comments on commit 0cc2f52

Please sign in to comment.