Last active
January 10, 2020 19:31
-
-
Save wryk/4a48034ba7558d23ed88b2e46ab4f9b7 to your computer and use it in GitHub Desktop.
group consecutive values in array with predicate
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 | |
$groupBy = function (array $xs, callable $f) { | |
reset($xs); | |
$r = []; | |
$t = []; | |
while (array_key_exists(key($xs), $xs)) { | |
$x = current($xs); | |
$t[] = $x; | |
$nx = next($xs); | |
if (!array_key_exists(key($xs), $xs) || !$f($x, $nx)) { | |
$r[] = $t; | |
$t = []; | |
} | |
} | |
return $r; | |
}; | |
$strictlyEqual = function ($a, $b) { | |
return $a === $b; | |
}; | |
var_dump($groupBy([], $strictlyEqual)); | |
var_dump($groupBy([false], $strictlyEqual)); | |
var_dump($groupBy([false, false, true, false, true, true], $strictlyEqual)); | |
var_dump($groupBy([1, 2, 1], $strictlyEqual)); | |
var_dump($groupBy([1, 2, 2, 3, 3, 4, 5, 6, 6], $strictlyEqual)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment