Skip to content

Commit

Permalink
refactor: Update Transpose operation in point free style. (#178)
Browse files Browse the repository at this point in the history
* refactor: Update `Transpose` operation in point free style.

* fix: Suppress ImpureMethodCall.

Based on suggestion from @weirdan on Slack.

> See https://psalm.dev/r/cc0354c625 and https://3v4l.org/LNuDT for simple examples.

And Bruce's suggestion:
> It'll still look pure to the outside: https://psalm.dev/r/6a4e6f8dde
  • Loading branch information
drupol authored Aug 22, 2021
1 parent 8fea387 commit d27116a
Showing 1 changed file with 29 additions and 30 deletions.
59 changes: 29 additions & 30 deletions src/Operation/Transpose.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,46 +26,45 @@ final class Transpose extends AbstractOperation
/**
* @pure
*
* @psalm-suppress ImpureMethodCall
*
* @return Closure(Iterator<TKey, T>): Generator<TKey, list<T>>
*/
public function __invoke(): Closure
{
return
$callbackForKeys =
/**
* @param Iterator<TKey, T> $iterator
* @param array $carry
* @param non-empty-array<int, TKey> $key
*
* @return Generator<TKey, list<T>>
* @return TKey
*/
static function (Iterator $iterator): Generator {
$mit = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);

foreach ($iterator as $iteratorIterator) {
$mit->attachIterator(new IterableIterator($iteratorIterator));
}
static fn (array $carry, array $key) => reset($key);

$callbackForKeys =
/**
* @param array $carry
* @param non-empty-array<int, TKey> $key
*
* @return TKey
*/
static fn (array $carry, array $key) => current($key);
$callbackForValues =
/**
* @param array $carry
* @param array<int, TKey> $key
* @param array<int, T> $value
*
* @return array<int, T>
*/
static fn (array $carry, array $key, array $value): array => $value;

$callbackForValues =
/**
* @param array $carry
* @param array<int, TKey> $key
* @param array<int, T> $value
*
* @return array<int, T>
*/
static fn (array $carry, array $key, array $value): array => $value;
/** @var Closure(Iterator<TKey, T>): Generator<TKey, list<T>> $pipe */
$pipe = Pipe::of()(
Reduce::of()(
static function (MultipleIterator $acc, iterable $iterable): MultipleIterator {
$acc->attachIterator(new IterableIterator($iterable));

/** @var Generator<TKey, list<T>> $associate */
$associate = Associate::of()($callbackForKeys)($callbackForValues)($mit);
return $acc;
}
)(new MultipleIterator(MultipleIterator::MIT_NEED_ANY)),
Flatten::of()(1),
Associate::of()($callbackForKeys)($callbackForValues)
);

return $associate;
};
// Point free style.
return $pipe;
}
}

0 comments on commit d27116a

Please sign in to comment.