Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
I recently needed to separate a collection of UI objects into subsequences whose combined width did not exceed the width of a view, so they could be wrapped into rows in that view. This seemed like a job for a chunking algorithm where the predicate would be allowed to reduce the elements, so I wrote that. I'm wondering whether others think it's generally useful enough to be included here.
Here's a simple example:
Note that a single element which fails the predicate is included in the resulting collection. More on that below.
This sort of chunking could be implemented using the Standard Library's existing
reduce(into:_)
, but then the trailing closure would be cluttered with all the logic to keep track of and generate the subsequences. I like that this new method abstracts that away so the closure is simply the predicate that determines how to chunk elements.Detailed Design
I've added
and
Handling single elements which fail the predicate
In my UI problem which motivated this, it so happened that no UI element could exceed the width of the view I needed to wrap them into. But it wouldn't be the case in general that a single element would be guaranteed not to fail the predicate. The current implementation includes such elements in the result, to satisfy the property shared by all the other chunking methods that the entire base collection is included in their result.
Documentation Plan
I updated Guides/Chunked.md with a description and example of the new method.
Test Plan
I added a series of tests for both the eager and lazy versions of the new method.
Source Impact
This only adds API. No existing API is changed or removed.
Checklist