From f5b16c8ff662bc898ea845a0cb62e9951d335ae6 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sat, 29 Apr 2023 10:45:13 +0900 Subject: [PATCH] Add toArrayPreservingKeys (#126) --- README.md | 1 + src/Standard.php | 8 ++++++++ tests/StandardTest.php | 27 +++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/README.md b/README.md index d5e318a..eb9e32b 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ All entry points always return an instance of the pipeline. | `max()` | Finds the highest value. | `max` | | `min()` | Finds the lowest value. | `min` | | `toArray()` | Returns an array with all values. Eagerly executed. | `dict`, `ToDictionary` | +| `toArrayPreservingKeys()` | Returns an array with all values and keys. Eagerly executed. | | | `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) | | `finalVariance()` | Computes final statistics for the sequence. | | | `__construct()` | Can be provided with an optional initial iterator. Used in the `take()` function from above. | | diff --git a/src/Standard.php b/src/Standard.php index 9a51449..d9fda55 100644 --- a/src/Standard.php +++ b/src/Standard.php @@ -539,6 +539,14 @@ public function toArray(bool $preserve_keys = false): array return iterator_to_array($this, $preserve_keys); } + /** + * Returns all values preserving keys. This is a terminal operation. + */ + public function toArrayPreservingKeys(): array + { + return $this->toArray(true); + } + /** * {@inheritdoc} * diff --git a/tests/StandardTest.php b/tests/StandardTest.php index 5759a3b..8d8364f 100644 --- a/tests/StandardTest.php +++ b/tests/StandardTest.php @@ -369,6 +369,19 @@ public function testToArrayWithArray(): void ], $pipeline->toArray(true)); } + public function testToArrayWithArrayPreservingKeys(): void + { + $pipeline = fromArray([ + 'a' => 1, + 'b' => 2, + ]); + + $this->assertSame([ + 'a' => 1, + 'b' => 2, + ], $pipeline->toArrayPreservingKeys()); + } + public function testToArrayWithIterator(): void { $pipeline = map(function () { @@ -391,4 +404,18 @@ public function testToArrayWithIterator(): void 'b' => 2, ], $pipeline->toArray(true)); } + + public function testToArrayWithIteratorPreservingKeys(): void + { + $pipeline = map(function () { + yield 'a' => 1; + yield 'b' => 2; + yield 'b' => 3; + }); + + $this->assertSame([ + 'a' => 1, + 'b' => 3, + ], $pipeline->toArrayPreservingKeys()); + } }