forked from 12meses12katas/Enero-String-Calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCalculator.php
More file actions
89 lines (58 loc) · 2.19 KB
/
Copy pathStringCalculator.php
File metadata and controls
89 lines (58 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
class StringCalculator
{
const STANDARD_SEPARATOR = ',';
function add($command)
{
if ($command == "")
return 0;
list($header, $searches) = $this->headerAndSeparators($command);
$numberString = str_replace($header, '', $command);
$normalized = str_replace($searches, self::STANDARD_SEPARATOR, $numberString);
$numberArray = explode(self::STANDARD_SEPARATOR, $normalized);
$this->validateNoNegatives($numberArray);
$numberArray = $this->ignoreGreatherThanOneThousand($numberArray);
return array_sum($numberArray);
}
function ignoreGreatherThanOneThousand($numeros)
{
$numeros = array_filter($numeros, function ($value) {
return $value < 1000;
});
return $numeros;
}
function validateNoNegatives($numeros)
{
$negativos = array_filter($numeros, function ($value) {
return $value < 0;
});
if (count($negativos) > 0)
throw new Exception("negativos: " . implode(',', $negativos));
}
function headerAndSeparators($command)
{
$hookSeparatorType = strpos($command, '[');
if ($hookSeparatorType)
return $this->headerAndHookSeparators($command);
$customSeparator = substr($command, 0, 2) == '//';
if ($customSeparator)
return $this->headerAndCustomSeparators($command);
return array("", array('\n'));
}
function headerAndHookSeparators($command)
{
$clean = str_replace(array('//'), '', $command);
$separators = array('\n');
$separators[] = strtok($clean, '[]');
while ($separators[] = strtok('[]'));
$header = substr($command, 0, strpos($command, '\n') + 2);
$separators = array_slice($separators, 0, count($separators) - 2);
return array($header, $separators);
}
function headerAndCustomSeparators($command)
{
$command = str_replace(array('//'), '', $command);
list($separator, $command) = explode('\n', $command);
return array("//$separator\n", array('\n',$separator));
}
}