Skip to content

Instantly share code, notes, and snippets.

@nawarian
Created May 8, 2020 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nawarian/fc54755ad875198b1f48ab1afa0f5299 to your computer and use it in GitHub Desktop.
Save nawarian/fc54755ad875198b1f48ab1afa0f5299 to your computer and use it in GitHub Desktop.
A simple test class checking how a FizzBuzz function should behave.
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class FizzBuzzTest extends TestCase
{
/**
* @dataProvider fizzBuzzHappyCaseDataProvider
*/
public function testFizzBuzzHappyCases(int $start, int $end, string $expectedOutput): void
{
self::assertEquals($expectedOutput, fizzBuzz($start, $end));
}
public function fizzBuzzHappyCaseDataProvider(): array
{
return [
// Multiples of three become "Fizz"
[1, 4, '1,2,Fizz,4'],
// Multiples of five become "Buzz"
[1,5, '1,2,Fizz,4,Buzz'],
// Multiples of 15 become "Fizz Buzz"
[1, 20, '1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,Fizz Buzz,16,17,Fizz,19,Buzz'],
];
}
/**
* @dataProvider fizzBuzzFaultyCaseDataProvider
*/
public function testFizzBuzzExceptions(
int $start,
int $end,
string $expectedException,
string $expectedExceptionMessage
): void {
self::expectExceptionMessage($expectedExceptionMessage);
self::expectException($expectedException);
fizzBuzz($start, $end);
}
public function fizzBuzzFaultyCaseDataProvider(): array
{
return [
// Negative ranges are impossible
[1, -10, InvalidArgumentException::class, 'Invalid range: $end (-10) must be greater than $start (1).'],
];
}
}
@nawarian
Copy link
Author

nawarian commented May 8, 2020

A possible implementation:

<?php

declare(strict_types=1);

function fizzBuzz(int $start, int $end): string
{
    if ($end - $start <= 0) {
        throw new InvalidArgumentException(
            sprintf('Invalid range: $end (%d) must be greater than $start (%d).', $end, $start)
        );
    }

    // Allocate necessary memory
    $parts = array_fill($start, $end, null);

    for ($i = $start; $i <= $end; $i++) {
        $parts[$i] = $i;

        if ($i % 3 === 0) {
            $parts[$i] = 'Fizz';
        }

        if ($i % 5 === 0) {
            $parts[$i] = 'Buzz';
        }

        if ($i % 15 === 0) {
            $parts[$i] = 'Fizz Buzz';
        }
    }

    return implode(',', $parts);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment