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

scan() generates a sequence of accumulated values #155

Open
sanmai opened this issue Jun 15, 2024 · 0 comments
Open

scan() generates a sequence of accumulated values #155

sanmai opened this issue Jun 15, 2024 · 0 comments
Labels
feature-request Feature request

Comments

@sanmai
Copy link
Owner

sanmai commented Jun 15, 2024

$numbers = Pipeline\fromValues(1, 2, 3, 4, 5);

$runningTotal = $numbers->scan(function ($accumulator, $value) {
    return $accumulator + $value;
}, 0);

foreach ($runningTotal as $total) {
    echo $total . ', ';
}
// Output: 0, 1, 3, 6, 10, 15,

Possible implementation:

/**
 * Performs a scan operation on the pipeline.
 *
 * @param callable $func Function that takes the accumulator and an element and returns the new accumulator.
 * @param mixed $initial Initial value for the accumulator.
 * @return self
 */
public function scan(callable $func, $initial = null): self
{
    if (null === $initial) {
        $this->pipeline = self::makeNonRewindable($this->pipeline);
        $initial = $this->pipeline->current();
        $this->pipeline->next();
    }

    $this->pipeline = self::performScan($this->pipeline, $func, $initial);

    return $this;
}

private static function performScan(Generator $input, callable $func, $accumulator): Generator
{
    yield $accumulator;
    foreach ($input as $value) {
        $accumulator = $func($accumulator, $value);
        yield $accumulator;
    }
}
@sanmai sanmai added the feature-request Feature request label Jun 15, 2024
@sanmai sanmai changed the title scan() scan() generates a sequence of accumulated values Jun 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request Feature request
Projects
None yet
Development

No branches or pull requests

1 participant