Skip to content

Commit

Permalink
add the reduce() method which is a wrapper of the native array_reduce…
Browse files Browse the repository at this point in the history
…() method.
  • Loading branch information
amitmerchant1990 committed Sep 13, 2021
1 parent c46053b commit e14d87b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/ArrayUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,17 @@ public function search(string $searchParam)
{
return array_search($searchParam, $this->collection);
}

/**
* Wrapper method for array_reduce
*
* @param Closure $callback
* @param mixed $initial
*
* @return mixed
*/
public function reduce(Closure $callback, $initial = null)
{
return array_reduce($this->collection, $callback, $initial);
}
}
22 changes: 22 additions & 0 deletions tests/ArrayUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,26 @@ public function it_successfully_gets_array_values()

$this->assertEquals(['Peter', '41', 'USA'], ArrayUtils::getInstance()->collect($user)->getValues());
}

/** @test */
public function it_successfully_reduces_array()
{
$this->assertEquals(15, ArrayUtils::getInstance()
->collect([1, 2, 3, 4, 5])
->reduce(function($carry, $item) {
$carry += $item;
return $carry;
}));
}

/** @test */
public function it_successfully_reduces_array_with_initial_value()
{
$this->assertEquals(1200, ArrayUtils::getInstance()
->collect([1, 2, 3, 4, 5])
->reduce(function($carry, $item) {
$carry *= $item;
return $carry;
}, 10));
}
}

0 comments on commit e14d87b

Please sign in to comment.