I am looking for a way to split an array into chunks with a max value, but can't seem to find a solution.
Lets say we have the following code:
struct FooBar {
let value: Int
}
let array: [FooBar] = [
FooBar(value: 1),
FooBar(value: 2),
FooBar(value: 1),
FooBar(value: 1),
FooBar(value: 1),
FooBar(value: 2),
FooBar(value: 2),
FooBar(value: 1)
]
And we want to split this into chunks where the maxSize of FooBar.value doesn't exceed 3. The end result should be something like:
let ExpectedEndResult: [[FooBar]] = [
[
FooBar(value: 1),
FooBar(value: 2)
],
[
FooBar(value: 1),
FooBar(value: 1),
FooBar(value: 1)
],
[
FooBar(value: 2),
],
[
FooBar(value: 2),
FooBar(value: 1)
]
]
I've written this so far, but there is an issue when a 3rd item could be added, also... I believe there must be simpler way but I just can't think of one right now:
extension Array where Element == FooBar {
func chunked(maxValue: Int) -> [[FooBar]] {
var chunks: [[FooBar]] = []
var chunk: [FooBar] = []
self.enumerated().forEach { key, value in
chunk.append(value)
if self.count-1 > key {
let next = self[key+1]
if next.value + value.value > maxValue {
chunks.append(chunk)
chunk = []
}
} else {
chunks.append(chunk)
}
}
return chunks
}
}
Any suggestions?