Last active
December 23, 2015 15:59
-
-
Save peinwag/6659063 to your computer and use it in GitHub Desktop.
tdd session phpunconference2013
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 | |
class StringCalculator | |
{ | |
public function add($numbers) | |
{ | |
$separators = array(',', "\n"); | |
$matches = null; | |
preg_match_all("~^\[(.)\]*~", $numbers, $matches); | |
if(isset($matches[1][0]) && $matches[1][0] != null) { | |
$separators[] = $matches[1][0]; | |
$numbers = substr($numbers, strlen($matches[0][0]) , strlen($numbers) - strlen($matches[0][0])); | |
} | |
foreach ($separators as $separator) { | |
if(strstr($numbers, $separator)) { | |
break; | |
} | |
} | |
$numbers = explode($separator, $numbers); | |
return array_sum($numbers); | |
} | |
} | |
class StringCalculatorTest extends PHPUnit_Framework_TestCase | |
{ | |
public function testAddEmptyString() | |
{ | |
$stringCalculator = new StringCalculator(); | |
$result = $stringCalculator->add(""); | |
$this->assertSame(0, $result); | |
} | |
public function testAddOneNumber() | |
{ | |
$stringCalculator = new StringCalculator(); | |
$result = $stringCalculator->add("7"); | |
$this->assertSame(7, $result); | |
} | |
public function testAddTwoNumbersCommaSeparated() | |
{ | |
$stringCalculator = new StringCalculator(); | |
$result = $stringCalculator->add("3,8"); | |
$this->assertSame(11, $result); | |
} | |
public function testAddThreeNumbersCommaSeparated() | |
{ | |
$stringCalculator = new StringCalculator(); | |
$result = $stringCalculator->add("3,8,7"); | |
$this->assertSame(18, $result); | |
} | |
public function testAddTwoNumbersNewlineSeparated() | |
{ | |
$stringCalculator = new StringCalculator(); | |
$result = $stringCalculator->add("3\n8"); | |
$this->assertSame(11, $result); | |
} | |
public function testAddThreeNumbersConfigurableDelimiterSeparated() | |
{ | |
$stringCalculator = new StringCalculator(); | |
$result = $stringCalculator->add("[q]3q8q7"); | |
$this->assertSame(18, $result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment