Last active
June 13, 2024 16:32
-
-
Save navarr/7de5b769fe59c8d5dcffc4d56d56df33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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