Skip to content

Commit 05a4b90

Browse files
committed
added Iterables::fromPairs()
1 parent 1f63691 commit 05a4b90

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Utils/Iterables.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,21 @@ public static function mapWithKeys(iterable $iterable, callable $transformer): \
178178
}
179179

180180

181+
/**
182+
* Creates an iterator from an array of [key, value] pairs.
183+
* @template K
184+
* @template V
185+
* @param iterable<array{K, V}> $pairs
186+
* @return \Generator<K, V>
187+
*/
188+
public static function fromPairs(iterable $pairs): \Generator
189+
{
190+
foreach ($pairs as $pair) {
191+
yield $pair[0] => $pair[1];
192+
}
193+
}
194+
195+
181196
/**
182197
* Creates a repeatable iterator from a factory function.
183198
* The factory is called every time the iterator is iterated.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Iterables::fromPairs()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Iterables;
10+
use Tester\Assert;
11+
12+
require __DIR__ . '/../bootstrap.php';
13+
14+
15+
// Basic test
16+
$result = [];
17+
$pairs = [['a', 1], ['a', 2], ['c', 3]];
18+
foreach (Iterables::fromPairs($pairs) as $k => $v) {
19+
$result[] = [$k, $v];
20+
}
21+
Assert::same($pairs, $result);
22+
23+
24+
// Test with null key
25+
$result = [];
26+
$pairs = [[null, 'null'], [[], 'array']];
27+
foreach (Iterables::fromPairs($pairs) as $k => $v) {
28+
$result[] = [$k, $v];
29+
}
30+
Assert::same($pairs, $result);
31+
32+
33+
// Test with iterator
34+
$result = [];
35+
$pairs = [['a', 1], ['b', 2]];
36+
foreach (Iterables::fromPairs(new ArrayIterator($pairs)) as $k => $v) {
37+
$result[] = [$k, $v];
38+
}
39+
Assert::same($pairs, $result);

0 commit comments

Comments
 (0)