-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Array+SwiftLint.swift
65 lines (56 loc) · 1.96 KB
/
Array+SwiftLint.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import Dispatch
import Foundation
import SourceKittenFramework
extension Array where Element: NSTextCheckingResult {
func ranges() -> [NSRange] {
return map { $0.range }
}
}
extension Array where Element == SyntaxToken {
var kinds: [SyntaxKind] {
return compactMap { SyntaxKind(rawValue: $0.type) }
}
}
extension Array where Element: Equatable {
var unique: [Element] {
var uniqueValues = [Element]()
for item in self where !uniqueValues.contains(item) {
uniqueValues.append(item)
}
return uniqueValues
}
}
extension Array {
static func array(of obj: Any?) -> [Element]? {
if let array = obj as? [Element] {
return array
} else if let obj = obj as? Element {
return [obj]
}
return nil
}
func group<U: Hashable>(by transform: (Element) -> U) -> [U: [Element]] {
return Dictionary(grouping: self, by: { transform($0) })
}
func partitioned(by belongsInSecondPartition: (Element) throws -> Bool) rethrows ->
(first: ArraySlice<Element>, second: ArraySlice<Element>) {
var copy = self
let pivot = try copy.partition(by: belongsInSecondPartition)
return (copy[0..<pivot], copy[pivot..<count])
}
func parallelFlatMap<T>(transform: @escaping ((Element) -> [T])) -> [T] {
return parallelMap(transform: transform).flatMap { $0 }
}
func parallelCompactMap<T>(transform: @escaping ((Element) -> T?)) -> [T] {
return parallelMap(transform: transform).compactMap { $0 }
}
func parallelMap<T>(transform: (Element) -> T) -> [T] {
var result = ContiguousArray<T?>(repeating: nil, count: count)
return result.withUnsafeMutableBufferPointer { buffer in
DispatchQueue.concurrentPerform(iterations: buffer.count) { idx in
buffer[idx] = transform(self[idx])
}
return buffer.map { $0! }
}
}
}