Skip to content

Commit

Permalink
Merge 6ce63c8 into f5b16c8
Browse files Browse the repository at this point in the history
  • Loading branch information
sanmai authored Apr 29, 2023
2 parents f5b16c8 + 6ce63c8 commit 9758ed2
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ All entry points always return an instance of the pipeline.
| `flip()` | Swaps keys and values. | `array_flip` |
| `max()` | Finds the highest value. | `max` |
| `min()` | Finds the lowest value. | `min` |
| `count()` | Counts value. | `array_count` |
| `runningCount()` | Counts seen values using a reference argument. | |
| `toArray()` | Returns an array with all values. Eagerly executed. | `dict`, `ToDictionary` |
| `toArrayPreservingKeys()` | Returns an array with all values and keys. Eagerly executed. | |
| `runningVariance()` | Computes online statistics: sample mean, sample variance, standard deviation. | [Welford's method](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm) |
Expand Down
23 changes: 23 additions & 0 deletions src/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,29 @@ public function toArrayPreservingKeys(): array
return $this->toArray(true);
}

/**
* Counts seen values online.
*
* @param ?int &$count the current count; initialized unless provided
*
* @param-out int $count
*
* @return $this
*/
public function runningCount(
?int &$count
): self {
$count ??= 0;

$this->cast(static function ($input) use (&$count) {
++$count;

return $input;
});

return $this;
}

/**
* {@inheritdoc}
*
Expand Down
20 changes: 20 additions & 0 deletions tests/CountTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use function Pipeline\fromArray;
use function Pipeline\map;
use function Pipeline\take;
use function range;

/**
* @covers \Pipeline\Standard
Expand Down Expand Up @@ -61,4 +62,23 @@ public function testCountValues(): void
yield 2 => 3;
}));
}

public function testRunningCount(): void
{
$countEven = 1;

$pipeline = map(fn () => yield from range(0, 100))
->runningCount($countAll)
->filter(fn (int $n) => $n % 2)
->runningCount($countEven)
->filter(fn (int $n) => $n % 3);

$this->assertSame(0, $countAll);
$this->assertSame(1, $countEven);

$this->assertSame(33, $pipeline->count());

$this->assertSame(101, $countAll);
$this->assertSame(50, $countEven - 1);
}
}

0 comments on commit 9758ed2

Please sign in to comment.