Last active
October 24, 2019 20:40
-
-
Save Braunson/d2c971e81e45234dc2d9ca08a6c9e5e7 to your computer and use it in GitHub Desktop.
Laravel Collection Macro trimEndWhile
This file contains hidden or 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
Collection::macro('trimEndWhile', function ($callback) { | |
$collection = new static($this->items); | |
while ($collection->count() && $callback($collection->last()) { | |
$collection->pop(); | |
} | |
return $collection; | |
}); | |
// Usage | |
$result = collect([10, 20, 30, 40, 50])->trimEndWhile(function ($i) { | |
return $i > 25; | |
}); | |
// Returns | |
// [10, 20] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment