Skip to content

Commit

Permalink
Add keys operation
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Sep 7, 2024
1 parent 19724d9 commit 11f1e25
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Nexus/Collection/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ public function getIterator(): \Traversable
yield from $this->innerIterator->getIterator();
}

public function keys(): CollectionInterface
{
return new self(static function (iterable $collection): iterable {
foreach ($collection as $key => $_) {
yield $key;
}
}, [$this]);
}

public function values(): CollectionInterface
{
return new self(static function (iterable $collection): iterable {
Expand Down
2 changes: 2 additions & 0 deletions src/Nexus/Collection/CollectionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@
*
* @extends \IteratorAggregate<TKey, T>
* @extends Operation\All<TKey, T>
* @extends Operation\Keys<TKey, T>
* @extends Operation\Values<TKey, T>
*/
interface CollectionInterface extends
\Countable,
\IteratorAggregate,
Operation\All,
Operation\Keys,
Operation\Values
{
/**
Expand Down
36 changes: 36 additions & 0 deletions src/Nexus/Collection/Operation/Keys.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <paulbalandan@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\Collection\Operation;

use Nexus\Collection\CollectionInterface;

/**
* @template TKey
* @template T
*/
interface Keys
{
/**
* Returns a new collection from keys of the original collection as
* the new values.
*
* ```
* Collection::wrap(['banana' => 1, 'apple' => 2])->keys();
* => Collection(['banana', 'apple'])
* ```
*
* @return CollectionInterface<int, TKey>
*/
public function keys(): CollectionInterface;
}
13 changes: 13 additions & 0 deletions tests/Collection/AbstractCollectionTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@ public function testCount(): void
self::assertCount(2, $this->collection([1, 2]));
}

public function testKeys(): void
{
$collection = $this->collection(static function (): \Generator {
yield 'bananas' => 5;

yield 'apples' => 4;

yield 'oranges' => 7;
});

self::assertSame(['bananas', 'apples', 'oranges'], $collection->keys()->all());
}

public function testValues(): void
{
$collection = $this->collection(static function (): \Generator {
Expand Down

0 comments on commit 11f1e25

Please sign in to comment.