Skip to content

Commit

Permalink
Add toArrayPreservingKeys (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
sanmai authored Apr 29, 2023
1 parent e625c13 commit f5b16c8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. | |
Expand Down
8 changes: 8 additions & 0 deletions src/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}
*
Expand Down
27 changes: 27 additions & 0 deletions tests/StandardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand All @@ -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());
}
}

0 comments on commit f5b16c8

Please sign in to comment.