Skip to content

[5.4] Create a static "times" method on the collection - #18457

Merged
taylorotwell merged 1 commit into
laravel:5.4from
JosephSilber:collection-range
Mar 25, 2017
Merged

[5.4] Create a static "times" method on the collection#18457
taylorotwell merged 1 commit into
laravel:5.4from
JosephSilber:collection-range

Conversation

@JosephSilber

@JosephSilber JosephSilber commented Mar 23, 2017

Copy link
Copy Markdown
Contributor

This is extremely useful to whip up a quick list of stuff, whether in a test or in production:

$slugs = Collection::times(5, function ($number) {
    return 'slug-'.$number;
});

// ['slug-1', 'slug-2', 'slug-3', 'slug-4', 'slug-5'];

You can also use it with factories, for example if you want sequential numbers:

$products = Collection::times(5, function ($number) {
    return factory(Product::class)->create(['name' => 'Product #'.$number]);
});

@JosephSilber
JosephSilber force-pushed the collection-range branch 7 times, most recently from c2e28be to c2c83b8 Compare March 23, 2017 02:22
@JosephSilber JosephSilber changed the title [5.4] Create a static range method on the collection [5.4] Create a static "times" method on the collection Mar 23, 2017
@JosephSilber
JosephSilber force-pushed the collection-range branch 3 times, most recently from 5c07a42 to 7b08ced Compare March 23, 2017 02:27
@taylorotwell

Copy link
Copy Markdown
Member

The name of the method needs work maybe? times in Ruby is more like an each operation, so it's a little confusing to me?

@JosephSilber

JosephSilber commented Mar 23, 2017

Copy link
Copy Markdown
Contributor Author

This is an each (plus a map).


There's nothing stopping you from just ignoring everything else:

Collection::times(5, function () {
    echo 'I will be logged 5 times.';
});

@deleugpn

Copy link
Copy Markdown
Contributor

Collection::repeat?

@jmarcher

jmarcher commented Mar 24, 2017

Copy link
Copy Markdown
Contributor

Failing test:

    public function testTimesWithZeroMethod()
    {
        $this->assertEquals([], Collection::times(0, function ($number) {
            return 'do-not-enter-'.$number;
        })->all());
    }

@JosephSilber

JosephSilber commented Mar 24, 2017 via email

Copy link
Copy Markdown
Contributor Author

@jmarcher

Copy link
Copy Markdown
Contributor

Negative numbers do not make sense but if we I see a method called "times" and give a 0 as parameter I expect that it executes zero times

@JosephSilber
JosephSilber force-pushed the collection-range branch 3 times, most recently from e4f21d6 to 2f03d11 Compare March 24, 2017 18:11
@JosephSilber

Copy link
Copy Markdown
Contributor Author

@jmarcher makes sense. Added it 👍

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants