Skip to content

Commit

Permalink
[Chucked] Add chunks(of:) information on the Chunked guides
Browse files Browse the repository at this point in the history
  • Loading branch information
LucianoPAlmeida committed Dec 24, 2020
1 parent 93c98d2 commit e8e4e43
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions Guides/Chunked.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]

Break a collection into subsequences where consecutive elements pass a binary
predicate, or where all elements in each chunk project to the same value.
predicate, or where all elements in each chunk project to the same value.

Also, includes a `chunks(of size:)` that breaks a collection into subsequences
of a given size.

There are two variations of the `chunked` method: `chunked(by:)` and
`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive
Expand All @@ -26,17 +29,31 @@ let chunks = names.chunked(on: \.first!)
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
```

These methods are related to the [existing SE proposal][proposal] for chunking a
collection into subsequences of a particular size, potentially named something
like `chunked(length:)`. Unlike the `split` family of methods, the entire
collection is included in the chunked result — joining the resulting chunks
recreates the original collection.
The `chunks(of:)` takes a `size` parameter (required to be > 0) and separates
the collection into `n` chunks of this given size. If the size parameter is
evenly divided by the count of the base `Collection` all the chunks will have
the count equals to size. Otherwise, the last chunk will contain the remaining elements.

```swift
let names = ["David", "Kyle", "Karoy", "Nate"]
let evenly = names.chunks(of: 2)
// [["David", "Kyle"], ["Karoy", "Nate"]]

let remaining = names.chunks(of: 3)
// [["David", "Kyle", "Karoy"], "Nate"]]
```

The `chunks(of:)` is the method of the [existing SE proposal][proposal].
Unlike the `split` family of methods, the entire collection is included in the
chunked result — joining the resulting chunks recreates the original collection.

```swift
c.elementsEqual(c.chunked(...).joined())
// true
```

Check the [proposal][proposal] detailed design section for more info.

[proposal]: https://github.com/apple/swift-evolution/pull/935

## Detailed Design
Expand Down

0 comments on commit e8e4e43

Please sign in to comment.