Skip to content

Commit

Permalink
feat: Fix head to return one element
Browse files Browse the repository at this point in the history
  • Loading branch information
omitobi committed Apr 29, 2024
1 parent 1e96128 commit e53c765
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
27 changes: 25 additions & 2 deletions src/Traits/ArrayPrefix.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Transprime\Arrayed\Exceptions\ArrayedException;
use Transprime\Arrayed\Interfaces\ArrayedInterface;
use Transprime\Arrayed\Types\Undefined;

/**
* Trait ArrayPrefix
Expand Down Expand Up @@ -80,16 +81,38 @@ public function keysExists(array $needles, bool $all = true): bool
: (!$intersect->empty());
}

public function head(bool $preserveKeys = false): ArrayedInterface
/**
* @throws ArrayedException
* @return ArrayedInterface|mixed
*/
public function head(bool $preserveKeys = false)
{
return $this->slice(0, 1, $preserveKeys);
return self::makeArrayed(
$this->when($this->getWorkableItem())
->slice(0, 1, $preserveKeys)
->values()
->offsetGet(0)
);
}

public function tail(): ArrayedInterface
{
return $this->slice(1);
}

private function when($truthyValue, $default = Undefined::class)
{
if ($truthyValue) {
return $this;
}

if ($default === Undefined::class || $default instanceof Undefined) {
throw new \InvalidArgumentException('Value cannot be resolved');
}

return $this->setResult($default);
}

/**
* Forward the calls to `array_*` that is not yet implemented
* <br>
Expand Down
13 changes: 9 additions & 4 deletions tests/ArrayPrefixTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,16 +182,21 @@ public function testHead(): void
$data = ['a', 'b', 'c', 'd'];

$this->assertSame(
['a'],
arrayed($data)->head()->result(),
'a',
arrayed($data)->head(),
);

$data = ['a' => 'b', 'c' => 'd'];

$this->assertSame(
['a' => 'b'],
arrayed($data)->head()->result(),
'b',
arrayed($data)->head(),
);

// Test empty.
$this->expectException(\InvalidArgumentException::class);

arrayed([])->head();
}

public function testTail(): void
Expand Down

0 comments on commit e53c765

Please sign in to comment.