Skip to content

Instantly share code, notes, and snippets.

@abdumu
Last active December 23, 2017 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdumu/7f71d0d04abe7271d2de1a3a0178fe2d to your computer and use it in GitHub Desktop.
Save abdumu/7f71d0d04abe7271d2de1a3a0178fe2d to your computer and use it in GitHub Desktop.
[Laravel] Improved version of Collection->map as a macro (you can add it at AppServiceProvider.php boot method)
<?php
/*
* Improved version of Collection->map method
*
* @param callable $callback
*
* @return Illuminate\Support\Collection
*/
Illuminate\Support\Collection::macro('loop', function(callable $callback){
$items = [];
$loop = (object) ['count' => count($this->items), 'index' => -1, 'iteration' => 0, 'remaining' => count($this->items)];
foreach($this->items as $key => $item) {
$loop->index++;
$loop->iteration++;
$loop->remaining--;
$loop->first = $loop->index === 0;
$loop->last = $loop->index === $loop->count - 1;
$loop->even = ($loop->index + 1) % 2 === 0;
$loop->odd = ! $loop->even;
$items[$key] = $callback($item, $key, $loop);
}
return new static($items);
});
@abdumu
Copy link
Author

abdumu commented Dec 22, 2017

Example:

$array1 = collect(range(1, 100));

$array2 =  $array1->loop(function($item, $key, $loop){
    if($loop->first){
        return 'first';
    }

    if ($loop->last) {
        return 'last';
    }


    if ($loop->even) {
        return 'even';
    }
    
    if($loop->odd){
        return 'odd';
    }
    
    return $item++;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment