Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions src/Array/ArraySingle.php
Original file line number Diff line number Diff line change
Expand Up @@ -439,18 +439,17 @@ public static function maxBy(array $array, callable $callback): mixed
*/
public static function median(array $array): float|int
{
$values = array_values(
array_filter(
$array,
static fn(mixed $value): bool => is_int($value) || is_float($value) || (is_string($value) && is_numeric($value)),
),
);
$values = [];
foreach ($array as $value) {
if (is_int($value) || is_float($value) || (is_string($value) && is_numeric($value))) {
$values[] = (float) $value;
}
}

if ($values === []) {
return 0;
}

$values = array_map(static fn(mixed $value): float => (float) $value, $values);
sort($values, SORT_NUMERIC);
$count = count($values);
$mid = intdiv($count, 2);
Expand Down
4 changes: 2 additions & 2 deletions src/Config/Concerns/BaseConfigTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function append(string $key, mixed $value): bool
*/
public function changed(string $snapshot = 'default'): bool
{
if (!array_key_exists($snapshot, $this->snapshots)) {
if (!isset($this->snapshots[$snapshot])) {
return true;
}

Expand Down Expand Up @@ -501,7 +501,7 @@ public function replace(array $items): bool
public function restore(string $name = 'default'): bool
{
$this->assertWritable();
if (!array_key_exists($name, $this->snapshots)) {
if (!isset($this->snapshots[$name])) {
return false;
}

Expand Down
5 changes: 5 additions & 0 deletions tests/Feature/ArraySingleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
expect(ArraySingle::avg($values))->toBe(4);
});

it('ignores non-numeric values when calculating median', function () {
expect(ArraySingle::median([1, '2', 7.5, 'ignore', null]))->toBe(2.0)
->and(ArraySingle::median(['ignore', null]))->toBe(0);
});

it('searches an array for a callback condition', function () {
$data = [1, 2, 3, 4];
$key = ArraySingle::search($data, fn ($value) => $value === 3);
Expand Down