Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Update Window operation in point free style. #179

Merged
merged 7 commits into from
Aug 22, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -3999,9 +3999,13 @@ public function it_can_when(): void

public function it_can_window(): void
{
$this::fromIterable(range('a', 'z'))
$this::fromIterable(range('a', 'c'))
->window(0)
->shouldIterateAs(range('a', 'z'));
->shouldIterateAs([
['a'],
['b'],
['c'],
]);
AlexandruGG marked this conversation as resolved.
Show resolved Hide resolved

$this::fromIterable(range('a', 'z'))
->window(2)
Expand Down
37 changes: 16 additions & 21 deletions src/Operation/Window.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,27 +32,22 @@ public function __invoke(): Closure
{
return
/**
* @return Closure(Iterator<TKey, T>): Generator<TKey, T|list<T>>
* @return Closure(Iterator<TKey, T>): Generator<TKey, list<T>>
*/
static fn (int $size): Closure =>
/**
* @param Iterator<TKey, T> $iterator
*
* @return Generator<TKey, list<T>|T>
*/
static function (Iterator $iterator) use ($size): Generator {
if (0 === $size) {
return yield from $iterator;
}

++$size;
$size *= -1;

$stack = [];

foreach ($iterator as $key => $current) {
yield $key => $stack = array_slice([...$stack, $current], $size);
}
};
static function (int $size): Closure {
/** @var Closure(Iterator<TKey, T>): Generator<TKey, list<T>> $reduction */
$reduction = Reduction::of()(
/**
* @param list<T> $stack
* @param T $current
*
* @return list<T>
*/
static fn (array $stack, $current): array => array_slice([...$stack, $current], ++$size * -1)
)([]);

// Point free style.
return $reduction;
};
}
}