Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array Product puzzle
<?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 <caspar@iCasparWebDevelopment.com>
* @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 <caspar@iCasparWebDevelopment.com>
* @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