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

[8.x] Add collection sliding method #37751

Merged
merged 1 commit into from
Jun 21, 2021

Conversation

JosephSilber
Copy link
Member

@JosephSilber JosephSilber commented Jun 20, 2021

This method was extracted from this old PR.


Adds a sliding method to the collection, which creates chunks representing a "sliding window" view of the items in the collection:

Collection::times(5)->sliding(2); // [[1, 2], [2, 3], [3, 4], [4, 5]]
Collection::times(5)->sliding(3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Collection::times(5)->sliding(3, step: 2); // [[1, 2, 3], [3, 4, 5]]

Examples:

  1. Imagine you have a collection of nodes, which you want to link up into a linked list.

    The sliding method makes that really trivial:

    $nodes->sliding(2)->eachSpread(fn ($parent, $child) => $parent->next = $child);

    You can see similar usage in the original PR.

  2. Or imagine you have a list of transactions, and want to fill in their running total:

    $transactions->sliding(2)->eachSpread(
        fn ($previous, $current) => $transaction->total = $previous->total + $current->amount
    );

@jesseschutt
Copy link
Contributor

This would have come in quite handy in a situation where I had to compare a collection of Carbon instances and confirm each was within 15 minutes of the previous!

@michaeldyrynda
Copy link
Contributor

That second example is something I had to implement in my last job, where we wanted to show time between consecutive records showing time offline between connected sessions. Being able to have a a chunk of that functionality built in to the framework would have saved headaches and a good few lines of code. If only I knew to search for a 'sliding window', I could've saved myself the headache.

@taylorotwell taylorotwell merged commit 4be3354 into laravel:8.x Jun 21, 2021
@JosephSilber JosephSilber deleted the collection-sliding branch June 21, 2021 18:33
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