Created
November 6, 2018 20:04
-
-
Save iCaspar/8c9bc7959880b0ae7d3e8cd0e231dbea to your computer and use it in GitHub Desktop.
Array Product puzzle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Unit tests for Product of Array Items puzzle. | |
* | |
* @see https://www.codewars.com/kata/product-of-array-items/ | |
* | |
* Requirements: Calculate the product of all elements in an array. | |
* If the array is NULL or empty, return NULL | |
* | |
* @author Caspar Green <[email protected]> | |
* @since 1.0.0 | |
*/ | |
declare(strict_types=1); | |
namespace Cata\Tests\Unit\ArrayPuzzles; | |
use Cata\ArrayPuzzles\ArrayProducts; | |
use PHPUnit\Framework\TestCase; | |
class ArrayProductsTest extends TestCase | |
{ | |
/** | |
* Test getArrayProduct() should return null when the array is empty of null. | |
* | |
* @since 1.0.0 | |
* | |
* @return void | |
*/ | |
public function testGetArrayProductShouldReturnNullWhenArrayEmptyOrNull(): void | |
{ | |
$arrayProduct = new ArrayProducts(); | |
$this->assertNull($arrayProduct->getArrayProduct(null)); | |
$this->assertNull($arrayProduct->getArrayProduct([])); | |
} | |
public function testGetArrayProductShouldReturnArrayProductWhenArray(): void | |
{ | |
$arrayProduct = new ArrayProducts(); | |
$this->assertEquals(0, $arrayProduct->getArrayProduct([1, 4, 6, 0])); | |
$this->assertEquals(48, $arrayProduct->getArrayProduct([1, 4, 6, 2])); | |
$this->assertEquals(-250, $arrayProduct->getArrayProduct([-1, 5, 5, 10])); | |
} | |
} | |
<?php | |
/** | |
* Product of Array Items puzzle. | |
* | |
* @package Cata\ArrayPuzzles | |
* @author Caspar Green <[email protected]> | |
* @since 1.0.0 | |
*/ | |
declare(strict_types=1); | |
namespace Cata\ArrayPuzzles; | |
/** | |
* Class ArrayProducts | |
* | |
* @package Cata\ArrayPuzzles | |
* @since 1.0.0 | |
*/ | |
class ArrayProducts | |
{ | |
/** | |
* Get the array product. | |
* | |
* @param array|null $array | |
* | |
* @since 1.0.0 | |
* | |
* @return int|null | |
*/ | |
public function getArrayProduct(?array $array): ?int | |
{ | |
if (empty($array)) { | |
return null; | |
} | |
$product = 1; | |
foreach ($array as $item) { | |
$product *= $item; | |
} | |
return $product; | |
} | |
// OR the built-in way | |
// public function getArrayProductShort(?array $array): ?int | |
// { | |
// return (empty($array)) ? null : array_product($array); | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment