Skip to content

Commit

Permalink
Fixed incorrect index calculation for A::findLastIndex()
Browse files Browse the repository at this point in the history
  • Loading branch information
meszaros-lajos-gyorgy committed Jul 25, 2021
1 parent 4814774 commit 1ae6704
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 28 deletions.
34 changes: 9 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand All @@ -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
```
Expand Down
8 changes: 5 additions & 3 deletions src/A.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down

0 comments on commit 1ae6704

Please sign in to comment.