diff --git a/src/Sequence.php b/src/Sequence.php index 75c3bda..31a8685 100644 --- a/src/Sequence.php +++ b/src/Sequence.php @@ -360,6 +360,25 @@ public function map(callable $function): self return $self; } + /** + * Create a new Sequence with the exact same number of elements but with a + * new type transformed via the given function + * + * @template S + * + * @param callable(T): S $map + * + * @return self + */ + public function mapTo(string $type, callable $map): self + { + /** @psalm-suppress MixedArgument */ + return $this->toSequenceOf( + $type, + static fn($value): \Generator => yield $map($value), + ); + } + /** * Pad the sequence to a defined size with the given element * diff --git a/src/Set.php b/src/Set.php index b3d2e41..d28fb26 100644 --- a/src/Set.php +++ b/src/Set.php @@ -315,6 +315,25 @@ public function map(callable $function): self return $self; } + /** + * Create a new Set with the exact same number of elements but with a + * new type transformed via the given function + * + * @template S + * + * @param callable(T): S $map + * + * @return self + */ + public function mapTo(string $type, callable $map): self + { + /** @psalm-suppress MixedArgument */ + return $this->toSetOf( + $type, + static fn($value): \Generator => yield $map($value), + ); + } + /** * Return a sequence of 2 sets partitioned according to the given predicate * diff --git a/tests/SequenceTest.php b/tests/SequenceTest.php index 5bb52fd..285e8df 100644 --- a/tests/SequenceTest.php +++ b/tests/SequenceTest.php @@ -411,6 +411,17 @@ public function testMap() $this->assertSame([1, 4, 9, 16], unwrap($b)); } + public function testMapTo() + { + $a = Sequence::ints(1, 2, 3, 4); + $b = $a->mapTo('string', fn($i) => (string) $i); + + $this->assertInstanceOf(Sequence::class, $b); + $this->assertNotSame($a, $b); + $this->assertSame('string', $b->type()); + $this->assertSame(['1', '2', '3', '4'], unwrap($b)); + } + public function testThrowWhenTryingToModifyValueTypeInMap() { $this->expectException(\TypeError::class); diff --git a/tests/SetTest.php b/tests/SetTest.php index f118d68..e345338 100644 --- a/tests/SetTest.php +++ b/tests/SetTest.php @@ -326,6 +326,17 @@ public function testMap() $this->assertSame([1, 4, 9, 16], unwrap($s2)); } + public function testMapTo() + { + $a = Set::ints(1, 2, 3, 4); + $b = $a->mapTo('string', fn($i) => (string) $i); + + $this->assertInstanceOf(Set::class, $b); + $this->assertNotSame($a, $b); + $this->assertSame('string', $b->type()); + $this->assertSame(['1', '2', '3', '4'], unwrap($b)); + } + public function testThrowWhenTryingToModifyValueTypeInMap() { $this->expectException(\TypeError::class);