Skip to content

Commit

Permalink
add method to do a 1-1 map to another type
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptouuuu committed Dec 15, 2019
1 parent 2e42f35 commit 4471cd8
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Sequence.php
Expand Up @@ -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<S>
*/
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
*
Expand Down
19 changes: 19 additions & 0 deletions src/Set.php
Expand Up @@ -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<S>
*/
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
*
Expand Down
11 changes: 11 additions & 0 deletions tests/SequenceTest.php
Expand Up @@ -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);
Expand Down
11 changes: 11 additions & 0 deletions tests/SetTest.php
Expand Up @@ -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);
Expand Down

0 comments on commit 4471cd8

Please sign in to comment.