Anahkiasen / underscore-php

A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel
http://anahkiasen.github.com/underscore-php/
1.12k stars 88 forks source link

Arrays::each improvement #44

Open ktalebian opened 10 years ago

ktalebian commented 10 years ago

When looping through an array, I always check to ensure the array key exists before calling Arrays::each.

Example: say I get a POST request that sometimes contains Input::get('shifts'). If shift exists, I then want to loop through. Currently, I do

if (Input::has('shifts'))
{
    Arrays::each(Input::get('shifts'), function($shift) { ... })
}

Implementing Laravel's array_get() and checking for false values inside Arrays::each would allow to shorten the above to

Arrays::each( array_get(Input::all(), 'shifts'), function($shift) { ... })

and the function Arrays::each($array, Closure $closure) can become

public static function each($array, Closure $closure)
{
    if (is_null($array) || empty($array)) return [];

    foreach ($array as $key => $value) {
        $array[$key] = $closure($value, $key);
    }

    return $array;
}

What do you think?

kirkbushell commented 10 years ago

I do not think this is a great idea, as you're now getting a combination of implementation details inside the each method, which I don't think is necessary. The first approach is much nicer and cleaner (aka, as is).

sergiors commented 9 years ago

You could use:

Arrays::each(Arrays::get(Input::all(), 'shifts', []), function($shift) { ... });