From 1ae6704a6f644767f6165059ee7fad57dc4c59ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A9sz=C3=A1ros=20Lajos?= Date: Sun, 25 Jul 2021 17:07:02 +0200 Subject: [PATCH] Fixed incorrect index calculation for A::findLastIndex() --- README.md | 34 +++++++++------------------------- src/A.php | 8 +++++--- 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index a95807d..32138e6 100644 --- a/README.md +++ b/README.md @@ -436,25 +436,17 @@ $result = A::findLast(fn($x) => $x["a"] === -4, $data); #### calls the given function on the elements of an array and returns the key for the first match. if there's no match it will return `null` ```php -$data = [ - ["a" => 8], - ["a" => 10], - ["a" => 12] -]; +$data = [1, 1, 1, 0, 0, 0, 0, 0]; -$result = A::findIndex(fn($x) => $x["a"] === 10, $data); +$result = A::findIndex(fn($x) => $x === 0, $data); -// $result = 1 +// $result = 3 ``` ```php -$data = [ - ["a" => 8], - ["a" => 10], - ["a" => 12] -]; +$data = [1, 1, 1, 0, 0, 0, 0, 0]; -$result = A::findIndex(fn($x) => $x["a"] === -4, $data); +$result = A::findIndex(fn($x) => $x === 2, $data); // $result = null ``` @@ -467,25 +459,17 @@ $result = A::findIndex(fn($x) => $x["a"] === -4, $data); #### calls the given function on the elements of an array and returns the key for the last match. if there's no match it will return `null` ```php -$data = [ - ["a" => 8], - ["a" => 10], - ["a" => 12] -]; +$data = [1, 1, 1, 0, 0, 0, 0, 0]; -$result = A::findLastIndex(fn($x) => $x["a"] > 3, $data); +$result = A::findLastIndex(fn($x) => $x === 1, $data); // $result = 2 ``` ```php -$data = [ - ["a" => 8], - ["a" => 10], - ["a" => 12] -]; +$data = [1, 1, 1, 0, 0, 0, 0, 0]; -$result = A::findLastIndex(fn($x) => $x["a"] > 500, $data); +$result = A::findLastIndex(fn($x) => $x === 2, $data); // $result = null ``` diff --git a/src/A.php b/src/A.php index d8c62ce..637e7a2 100644 --- a/src/A.php +++ b/src/A.php @@ -267,7 +267,7 @@ public static function findLast(callable $fn, array $data) { return self::find($fn, self::reverse($data)); } - // A::findIndex(x => x.a === 10, [['a' => 8], ['a' => 10]]) -> 1 + // A::findIndex(x => x === 1, [1, 1, 1, 0, 0, 0, 0, 0]) -> 3 public static function findIndex(callable $fn, array $data): ?int { if (self::isEmpty($data)) { return null; @@ -282,10 +282,12 @@ public static function findIndex(callable $fn, array $data): ?int { return null; } - // A::findLastIndex(x => x.a > 3, [['a' => 8], ['a' => 10]]) -> 1 + // A::findLastIndex(x => x === 1, [1, 1, 1, 0, 0, 0, 0, 0]) -> 2 public static function findLastIndex(callable $fn, array $data): ?int { - return self::findIndex($fn, self::reverse($data)); + $size = A::length($data); + $idx = self::findIndex($fn, self::reverse($data)); + return $idx === null ? null : $size - $idx - 1; } // A::any(x => x.a === 10, [['a' => 8], ['a' => 10]]) -> true