Skip to content

Commit f5b16c8

Browse files
authored
Add toArrayPreservingKeys (#126)
1 parent e625c13 commit f5b16c8

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ All entry points always return an instance of the pipeline.
125125
| `max()` | Finds the highest value. | `max` |
126126
| `min()` | Finds the lowest value. | `min` |
127127
| `toArray()` | Returns an array with all values. Eagerly executed. | `dict`, `ToDictionary` |
128+
| `toArrayPreservingKeys()` | Returns an array with all values and keys. Eagerly executed. | |
128129
| `runningVariance()` | Computes online statistics: sample mean, sample variance, standard deviation. | [Welford's method](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm) |
129130
| `finalVariance()` | Computes final statistics for the sequence. | |
130131
| `__construct()` | Can be provided with an optional initial iterator. Used in the `take()` function from above. | |

src/Standard.php

+8
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,14 @@ public function toArray(bool $preserve_keys = false): array
539539
return iterator_to_array($this, $preserve_keys);
540540
}
541541

542+
/**
543+
* Returns all values preserving keys. This is a terminal operation.
544+
*/
545+
public function toArrayPreservingKeys(): array
546+
{
547+
return $this->toArray(true);
548+
}
549+
542550
/**
543551
* {@inheritdoc}
544552
*

tests/StandardTest.php

+27
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,19 @@ public function testToArrayWithArray(): void
369369
], $pipeline->toArray(true));
370370
}
371371

372+
public function testToArrayWithArrayPreservingKeys(): void
373+
{
374+
$pipeline = fromArray([
375+
'a' => 1,
376+
'b' => 2,
377+
]);
378+
379+
$this->assertSame([
380+
'a' => 1,
381+
'b' => 2,
382+
], $pipeline->toArrayPreservingKeys());
383+
}
384+
372385
public function testToArrayWithIterator(): void
373386
{
374387
$pipeline = map(function () {
@@ -391,4 +404,18 @@ public function testToArrayWithIterator(): void
391404
'b' => 2,
392405
], $pipeline->toArray(true));
393406
}
407+
408+
public function testToArrayWithIteratorPreservingKeys(): void
409+
{
410+
$pipeline = map(function () {
411+
yield 'a' => 1;
412+
yield 'b' => 2;
413+
yield 'b' => 3;
414+
});
415+
416+
$this->assertSame([
417+
'a' => 1,
418+
'b' => 3,
419+
], $pipeline->toArrayPreservingKeys());
420+
}
394421
}

0 commit comments

Comments
 (0)