diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ac69b1..a2238b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * Changed sort(), sort_by(), max(), min(), max_by() and min_by() to order strings by code point. * Fixed max_by() and min_by() to error on mixed-type keys instead of returning arbitrary elements. * Fixed max() returning null or erroring when the first array element is falsy, e.g. max([0, 1]). +* Fixed sum() and join() to return 0 and an empty string respectively for empty arrays. * Fixed 0.0 to be truthy in filters and logical operators, like every other number. * Fixed the compiled runtime to apply JMESPath truthiness to || and &&. * Fixed @(foo), foo[-] and oversized index literals to throw syntax errors. diff --git a/src/FnDispatcher.php b/src/FnDispatcher.php index f4bb2ff..b1ee519 100644 --- a/src/FnDispatcher.php +++ b/src/FnDispatcher.php @@ -106,7 +106,7 @@ private function fn_join(array $args) $fn = function ($a, $b, $i) use ($args) { return $i ? ($a . $args[0] . $b) : $b; }; - return $this->reduce('join:0', $args[1], ['string'], $fn); + return $args[1] ? $this->reduce('join:0', $args[1], ['string'], $fn) : ''; } private function fn_keys(array $args) @@ -203,7 +203,7 @@ private function fn_sum(array $args) $fn = function ($a, $b) { return Utils::add($a, $b); }; - return $this->reduce('sum:0', $args[0], ['number'], $fn); + return $args[0] ? $this->reduce('sum:0', $args[0], ['number'], $fn) : 0; } private function fn_sort(array $args) diff --git a/tests/FnDispatcherTest.php b/tests/FnDispatcherTest.php index 2d1d893..75fcdfc 100644 --- a/tests/FnDispatcherTest.php +++ b/tests/FnDispatcherTest.php @@ -50,6 +50,22 @@ public function testContainsUsesJsonSemantics(): void $this->assertFalse($fn('contains', ['foobar', 123])); } + public function testSumOfEmptyArrayIsZero(): void + { + $fn = new FnDispatcher(); + + $this->assertSame(0, $fn('sum', [[]])); + $this->assertSame(3, $fn('sum', [[1, 2]])); + } + + public function testJoinOfEmptyArrayIsEmptyString(): void + { + $fn = new FnDispatcher(); + + $this->assertSame('', $fn('join', ['|', []])); + $this->assertSame('a|b', $fn('join', ['|', ['a', 'b']])); + } + public function testMaxAndMinCompareStringsByCodePoint(): void { $fn = new FnDispatcher();