-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathArray+Chunk.swift
45 lines (42 loc) · 1.21 KB
/
Array+Chunk.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// Array+Chunk.swift
//
// Advent of Code Tools
//
extension Array {
/// split an array into chunks so that for each chunk, `condition` is true
public func chunked(by condition: (Element, Element) -> Bool) -> [[Element]] {
guard !isEmpty else { return [] }
var result = [[Element]]()
var tmp = [Element]()
for index in 0 ..< self.count - 1 {
tmp.append(self[index])
if !condition(self[index], self[index + 1]) {
result.append(tmp)
tmp.removeAll()
}
}
tmp.append(self[self.count - 1])
result.append(tmp)
return result
}
}
extension Array {
/// split an array into groups that are separated at each element where `condition` is true
public func grouped(by condition: (Element) -> Bool) -> [[Element]] {
var tmp = [Element]()
var result = [[Element]]()
for element in self {
if condition(element) {
result.append(tmp)
tmp.removeAll()
} else {
tmp.append(element)
}
}
if !tmp.isEmpty {
result.append(tmp)
}
return result
}
}