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 Aug 4, 2014
1 parent df23566 commit 3c18fa3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

5.25 2014-08-04
- Added reduce method to Mojo::Collection.
- Fixed escaping bugs in Mojo::DOM::CSS.

5.24 2014-08-02
Expand Down
15 changes: 15 additions & 0 deletions lib/Mojo/Collection.pm
Expand Up @@ -73,6 +73,11 @@ sub pluck {
return $self->new(map { $_->$method(@args) } @$self);
}

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

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

sub shuffle { $_[0]->new(List::Util::shuffle @{$_[0]}) }
Expand Down Expand Up @@ -251,6 +256,16 @@ results.
# Equal to but more convenient than
my $new = $collection->map(sub { $_->$method(@args) });
=head2 reduce
my $result = $collection->reduce(sub {...});
my $result = $collection->reduce(sub {...}, $initial);
Reduce elements in collection with callback, the first element will be used as
initial value if none has been provided.
my $sum = $collection->reduce(sub { shift() + shift() });
=head2 reverse
my $new = $collection->reverse;
Expand Down
6 changes: 6 additions & 0 deletions t/mojo/collection.t
Expand Up @@ -112,6 +112,12 @@ is $collection->size, 1, 'right size';
$collection = c(5, 4, 3, 2, 1);
is $collection->size, 5, 'right size';

# reduce
$collection = c(2, 5, 4, 1);
is $collection->reduce(sub { shift() + shift() }), 12, 'right result';
is $collection->reduce(sub { shift() + shift() }, 5), 17, 'right result';
is c()->reduce(sub { shift() + shift() }), undef, 'no result';

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

0 comments on commit 3c18fa3

Please sign in to comment.