Added normalizer to help with concentrates and stones

This commit is contained in:
Chris 2019-07-11 12:21:14 +02:00
parent 796bd626c9
commit efe875bd05
2 changed files with 105 additions and 0 deletions

68
src/Helper/Normalizer.php Normal file
View File

@ -0,0 +1,68 @@
<?php
namespace NoccyLabs\Juicer\Helper;
/**
* Normalize percentages to a full 100%.
*
*/
class Normalizer
{
protected $inputs = [];
protected $ratio = 0;
/**
* Normalizer constructor.
*
* @param array The percentages indexed by a unique key
*/
public function __construct(array $inputPercents=[])
{
foreach ($inputPercents as $k=>$p)
$this->setPart($k, $p);
}
/**
* Set the percentage of a component.
*
* @param mixed The key used to access this part later
* @param float The percent of this part
*/
public function setPart($key, float $percent)
{
$this->inputs[$key] = $percent;
$total = array_sum(array_values($this->inputs));
$this->ratio = 100 / $total;
}
/**
* Get the original percentage of the key.
*
* @param mixed The key
* @return float Original percentage as provided
*/
public function getPercent($key)
{
if (!array_key_exists($key, $this->inputs))
throw new \Exception();
return floatval($this->inputs[$key]);
}
/**
* Get the normalized percentage where the added total equals 100%
*
* @param mixed The key
* @return float Normalized percentage as provided
*/
public function getNormalizedPercent($key)
{
if (!array_key_exists($key, $this->inputs))
throw new \Exception();
return floatval($this->inputs[$key]) * $this->ratio;
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace NoccyLabs\Juicer\Helper;
class NormalizerTest extends \PhpUnit\Framework\TestCase
{
public function testThatNormalizedPercentagesAreSane()
{
$normalizer = new Normalizer([
'A' => 10
]);
$this->assertEquals(10, $normalizer->getPercent("A"));
$this->assertEquals(100, $normalizer->getNormalizedPercent("A"));
$normalizer = new Normalizer([
'A' => 10,
'B' => 10,
]);
$this->assertEquals(10, $normalizer->getPercent("A"));
$this->assertEquals(50, $normalizer->getNormalizedPercent("A"));
$this->assertEquals(10, $normalizer->getPercent("B"));
$this->assertEquals(50, $normalizer->getNormalizedPercent("B"));
$normalizer = new Normalizer([
'A' => 2,
'B' => 8,
]);
$this->assertEquals(20, $normalizer->getNormalizedPercent("A"));
$this->assertEquals(80, $normalizer->getNormalizedPercent("B"));
}
}