Skip to content

Instantly share code, notes, and snippets.

@vzailskas
Created December 18, 2013 18:39
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 vzailskas/e77ce993438d6ebf631c to your computer and use it in GitHub Desktop.
Save vzailskas/e77ce993438d6ebf631c to your computer and use it in GitHub Desktop.
<?php
class Test extends PHPUnit_Framework_TestCase {
private $calc;
protected function setUp()
{
$this->calc = new Calc();
}
public function test_i_have_calc()
{
$this->assertInstanceOf('Calc', $this->calc);
}
public function test_sums_2_strings()
{
$this->assertSame(2, $this->calc->calculate('1 + 1'));
}
public function test_minus_2_strings()
{
$this->assertSame(1, $this->calc->calculate('2 - 1'));
}
public function test_minus_2_strings2()
{
$this->assertSame(-4, $this->calc->calculate('2 - 6'));
}
public function test_multiply_2_strings()
{
$this->assertSame(15, $this->calc->calculate('3 * 5'));
}
public function test_divide_2_strings()
{
$this->assertSame(3, $this->calc->calculate('6 / 2'));
}
public function test_multiple_operands()
{
$this->assertSame(2, $this->calc->calculate('6 + 2 - 6'));
}
public function test_operator_position()
{
$this->assertSame(6, $this->calc->calculate('2 + 2 * 2'));
}
public function test_operator2_position()
{
$this->assertSame(6, $this->calc->calculate('2 +2*2'));
}
}
class Calc
{
public function calculate($string)
{
$arr = $this->stringParser($string);
$result = $arr[0];
$primary = array('*', '/');
// Multiples and divisions
for($i = 1; $i < count($arr); $i = $i + 2) {
if(in_array($arr[$i], $primary)) {
$result = $this->_makeAction($result, $arr[$i], $arr[$i+1]);
unset($arr[$i]);
unset($arr[$i+1]);
}
}
// sums and minuses
for($i = 1; $i < count($arr); $i = $i + 2) {
$result = $this->_makeAction($result, $arr[$i], $arr[$i+1]);
}
return $result;
}
private function _makeAction($result, $action, $value)
{
switch ($action) {
case '+':
return $result + $value;
case '-':
return $result - $value;
case '*':
return $result * $value;
case '/':
return $result / $value;
}
}
private function stringParser($string) {
$data = array();
$lastNumber = false;
for($i = 0; $i < strlen($string); $i++) {
if($string[$i] != ' ') {
if(is_numeric($string[$i])) {
if($lastNumber)
$data[count($data)] .= $string[$i];
else {
$data[] = $string[$i];
$lastNumber = true;
}
} else {
$data[] = $string[$i];
$lastNumber = false;
}
}
}
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment