DEV Community

Discussion on: Daily Challenge #61 - Evolution Rate

Collapse
 
anwar_nairi profile image
Anwar

Since no one proposed a PHP solution, here I am!

if (!function_exists("getEvolutionRate")) {
    function getEvolutionRate(float $before, float $after): float {
        if ($before === 0.0) {
            return $after * 100;
        }

        if ($after === 0.0) {
            return -($before * 100);
        }

        return round(($after - $before) / $before * 100);
    }
}

if (!function_exists("getEvolutionRateMessage")) {
    function getEvolutionRateMessage(float $before, float $after): string {
        $evolutionRate = getEvolutionRate($before, $after);
        $evolutionRateToDisplay = abs($evolutionRate);
        $direction = $evolutionRate > 0 ? "positive" : "negative";

        return $evolutionRate === 0.0 ? "No evolution" : "A $direction evolution of $evolutionRateToDisplay%";
    }
}

getEvolutionRate() unit tests:

use PHPUnit\Framework\TestCase;

class GetEvolutionRateTest extends TestCase
{
    public function testShouldReturnPositiveRate()
    {
        $this->assertEquals(getEvolutionRate(11.29, 45.79), 306);
    }

    public function testShouldReturnOtherPositiveRate()
    {
        $this->assertEquals(getEvolutionRate(0, 27.35), 2735);
    }

    public function testShouldReturnNegativeRate()
    {
        $this->assertEquals(getEvolutionRate(95.12, 66.84), -30);
    }

    public function testShouldReturnOtherNegativeRate()
    {
        $this->assertEquals(getEvolutionRate(41.26, 0), -4126);
    }

    public function testShouldReturnZeroEvolution()
    {
        $this->assertEquals(getEvolutionRate(1.26, 1.26), 0);
    }
}

getEvolutionRateMessage() unit tests:

use PHPUnit\Framework\TestCase;

class GetEvolutionRateMessageTest extends TestCase
{
    public function testShouldReturnPositiveRateMessage()
    {
        $this->assertEquals(getEvolutionRateMessage(11.29, 45.79), "A positive evolution of 306%");
    }

    public function testShouldReturnOtherPositiveRateMessage()
    {
        $this->assertEquals(getEvolutionRateMessage(0, 27.35), "A positive evolution of 2735%");
    }

    public function testShouldReturnNegativeRateMessage()
    {
        $this->assertEquals(getEvolutionRateMessage(95.12, 66.84), "A negative evolution of 30%");
    }

    public function testShouldReturnOtherNegativeRateMessage()
    {
        $this->assertEquals(getEvolutionRateMessage(41.26, 0), "A negative evolution of 4126%");
    }

    public function testShouldReturnZeroEvolutionMessage()
    {
        $this->assertEquals(getEvolutionRateMessage(1.26, 1.26), "No evolution");
    }
}
Collapse
 
aminnairi profile image
Amin

I love those guards you are puting in your code. Really makes me want to go back and do PHP with you like the good ol'times!

Collapse
 
anwar_nairi profile image
Anwar • Edited

Let's do a side project together

Come come