Skip to content

Commit 208c9db

Browse files
committed
Add keys operation
1 parent 48906cb commit 208c9db

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-0
lines changed

src/Nexus/Collection/Collection.php

+9
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,15 @@ public function getIterator(): \Traversable
9898
yield from $this->innerIterator->getIterator();
9999
}
100100

101+
public function keys(): CollectionInterface
102+
{
103+
return new self(static function (iterable $collection): iterable {
104+
foreach ($collection as $key => $_) {
105+
yield $key;
106+
}
107+
}, [$this]);
108+
}
109+
101110
public function values(): CollectionInterface
102111
{
103112
return new self(static function (iterable $collection): iterable {

src/Nexus/Collection/CollectionInterface.php

+2
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@
1919
*
2020
* @extends \IteratorAggregate<TKey, T>
2121
* @extends Operation\All<TKey, T>
22+
* @extends Operation\Keys<TKey, T>
2223
* @extends Operation\Values<TKey, T>
2324
*/
2425
interface CollectionInterface extends
2526
\Countable,
2627
\IteratorAggregate,
2728
Operation\All,
29+
Operation\Keys,
2830
Operation\Values
2931
{
3032
/**
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of the Nexus framework.
7+
*
8+
* (c) John Paul E. Balandan, CPA <[email protected]>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Nexus\Collection\Operation;
15+
16+
use Nexus\Collection\CollectionInterface;
17+
18+
/**
19+
* @template TKey
20+
* @template T
21+
*/
22+
interface Keys
23+
{
24+
/**
25+
* Returns a new collection from keys of the original collection as
26+
* the new values.
27+
*
28+
* ```
29+
* Collection::wrap(['banana' => 1, 'apple' => 2])->keys();
30+
* => Collection(['banana', 'apple'])
31+
* ```
32+
*
33+
* @return CollectionInterface<int, TKey>
34+
*/
35+
public function keys(): CollectionInterface;
36+
}

tests/Collection/AbstractCollectionTestCase.php

+13
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ public function testCount(): void
5555
self::assertCount(2, $this->collection([1, 2]));
5656
}
5757

58+
public function testKeys(): void
59+
{
60+
$collection = $this->collection(static function (): \Generator {
61+
yield 'bananas' => 5;
62+
63+
yield 'apples' => 4;
64+
65+
yield 'oranges' => 7;
66+
});
67+
68+
self::assertSame(['bananas', 'apples', 'oranges'], $collection->keys()->all());
69+
}
70+
5871
public function testValues(): void
5972
{
6073
$collection = $this->collection(static function (): \Generator {

0 commit comments

Comments
 (0)