Skip to content

Instantly share code, notes, and snippets.

@navarr
Last active June 13, 2024 16:32
Show Gist options
  • Save navarr/7de5b769fe59c8d5dcffc4d56d56df33 to your computer and use it in GitHub Desktop.
Save navarr/7de5b769fe59c8d5dcffc4d56d56df33 to your computer and use it in GitHub Desktop.
<?php
class ArrayReduce
{
/**
* @template Value
* @template Key
* @template Result
* @param iterable<Key, Value> $toReduce
* @param callable(ArrayReduceResult<Result>, Value $item, Key $key): ArrayReduceResult<Result> $checkMethod
* @param mixed $initial
* @return mixed
*/
public function execute(iterable $toReduce, callable $checkMethod, mixed $initial = null): mixed
{
$reduceResult = new ArrayReduceResult($initial);
foreach ($toReduce as $key => $value) {
$reduceResult = $checkMethod($reduceResult, $value, $key);
if (!$reduceResult->continue) {
break;
}
}
return $reduceResult->result;
}
}
/**
* @template Result
*/
class ArrayReduceResult
{
public bool $continue;
/**
* @param Result|null $result
*/
public function __construct(public mixed $result) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment