Skip to content

Commit d854d5b

Browse files
author
MarkBaker
committed
Modify ABS() function to handle arrays, with appropriate unit tests
1 parent 93fccdc commit d854d5b

File tree

2 files changed

+39
-2
lines changed
  • src/PhpSpreadsheet/Calculation/MathTrig
  • tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig

2 files changed

+39
-2
lines changed

src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,31 @@
66

77
class Absolute
88
{
9+
private static function evaluateArray($numbers)
10+
{
11+
$result = [];
12+
foreach ($numbers as $number) {
13+
$result[] = self::evaluate($number);
14+
}
15+
16+
return $result;
17+
}
18+
919
/**
1020
* ABS.
1121
*
1222
* Returns the result of builtin function abs after validating args.
1323
*
1424
* @param mixed $number Should be numeric
1525
*
16-
* @return float|int|string Rounded number
26+
* @return float|int|string|array Rounded number
1727
*/
1828
public static function evaluate($number)
1929
{
30+
if (is_array($number)) {
31+
return self::evaluateArray($number);
32+
}
33+
2034
try {
2135
$number = Helpers::validateNumericNullBool($number);
2236
} catch (Exception $e) {

tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AbsTest.php

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig;
44

5+
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6+
57
class AbsTest extends AllSetupTeardown
68
{
79
/**
@@ -10,7 +12,7 @@ class AbsTest extends AllSetupTeardown
1012
* @param mixed $expectedResult
1113
* @param mixed $number
1214
*/
13-
public function testRound($expectedResult, $number = 'omitted'): void
15+
public function testAbsolute($expectedResult, $number = 'omitted'): void
1416
{
1517
$sheet = $this->getSheet();
1618
$this->mightHaveException($expectedResult);
@@ -28,4 +30,25 @@ public function providerAbs(): array
2830
{
2931
return require 'tests/data/Calculation/MathTrig/ABS.php';
3032
}
33+
34+
/**
35+
* @dataProvider providerAbsArray
36+
*/
37+
public function testAbsoluteArray(array $expectedResult, string $array): void
38+
{
39+
$calculation = Calculation::getInstance();
40+
41+
$formula = "=ABS({$array})";
42+
$result = $calculation->_calculateFormulaValue($formula);
43+
self::assertSame($expectedResult, $result);
44+
}
45+
46+
public function providerAbsArray(): array
47+
{
48+
return [
49+
'row vector' => [[[1, 0, 1]], '{-1, 0, 1}'],
50+
'column vector' => [[[1], [0], [1]], '{-1; 0; 1}'],
51+
'matrix' => [[[1, 0], [1, 1]], '{-1, 0; 1, -1}'],
52+
];
53+
}
3154
}

0 commit comments

Comments
 (0)