Page MenuHomeDevCentral

D3217.id8243.diff
No OneTemporary

D3217.id8243.diff

diff --git a/omnitools/src/Collections/BaseVector.php b/omnitools/src/Collections/BaseVector.php
--- a/omnitools/src/Collections/BaseVector.php
+++ b/omnitools/src/Collections/BaseVector.php
@@ -193,6 +193,37 @@
return new static($mappedVector);
}
+ /**
+ * Allows to map each vector elements into key/value pairs
+ * and collect them into a HashMap.
+ *
+ * @param callable $callable A method to return [$key, $value] array
+ *
+ * @return HashMap
+ */
+ public function mapToHashMap (callable $callable) : HashMap {
+ $argc = (new CallableElement($callable))->countArguments();
+
+ $map = new HashMap;
+ foreach ($this->items as $key => $value) {
+ $toAdd = match($argc) {
+ 0 => throw new InvalidArgumentException(self::CB_ZERO_ARG),
+ 1 => $callable($value),
+ default => $callable($key, $value),
+ };
+
+ if (!is_array($toAdd) || count($toAdd) != 2) {
+ throw new InvalidArgumentException(
+ "Callback must return an array with 2 items: [key, value]"
+ );
+ }
+
+ $map->set($toAdd[0], $toAdd[1]);
+ }
+
+ return $map;
+ }
+
public function flatMap (callable $callable) : self {
$argc = (new CallableElement($callable))->countArguments();
diff --git a/omnitools/tests/Collections/VectorTest.php b/omnitools/tests/Collections/VectorTest.php
--- a/omnitools/tests/Collections/VectorTest.php
+++ b/omnitools/tests/Collections/VectorTest.php
@@ -3,6 +3,7 @@
namespace Keruald\OmniTools\Tests\Collections;
+use Keruald\OmniTools\Collections\HashMap;
use Keruald\OmniTools\Collections\Vector;
use PHPUnit\Framework\TestCase;
@@ -177,6 +178,38 @@
$this->vector->flatMap($callback);
}
+ public function testMapToHashMap () : void {
+ $expected = [
+ 1 => 1,
+ 2 => 4,
+ 3 => 9,
+ 4 => 16,
+ 5 => 25,
+ ];
+
+ $fn = fn($value) => [$value, $value * $value];
+ $map = $this->vector->mapToHashMap($fn);
+
+ $this->assertInstanceOf(HashMap::class, $map);
+ $this->assertEquals($expected, $map->toArray());
+ }
+
+ public function testMapToHashMapWithCallbackWithoutArgument() : void {
+ $this->expectException(InvalidArgumentException::class);
+
+ $callback = function () {};
+ $this->vector->mapToHashMap($callback);
+ }
+
+ public function testMapToHashMapWithBadCallback () : void {
+ $this->expectException(InvalidArgumentException::class);
+
+ $callback = fn($key, $value) : bool => false; // not an array
+
+ $this->vector->mapToHashMap($callback);
+ }
+
+
public function testFilter () : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);

File Metadata

Mime Type
text/plain
Expires
Tue, Dec 24, 05:31 (17 h, 34 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2313583
Default Alt Text
D3217.id8243.diff (2 KB)

Event Timeline