Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Mar 25, 2017

Conversation

JosephSilber
Copy link
Contributor

@JosephSilber JosephSilber commented Mar 23, 2017

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
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
Copy link
Contributor Author

JosephSilber commented Mar 23, 2017

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
Contributor

Collection::repeat?

@jmarcher
Copy link
Contributor

jmarcher commented Mar 24, 2017

Failing test:

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

@JosephSilber
Copy link
Contributor Author

JosephSilber commented Mar 24, 2017 via email

@jmarcher
Copy link
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
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