1
1
mirror of https://github.com/qvacua/vimr.git synced 2024-11-28 02:54:31 +03:00
vimr/VimR/SwiftCommons.swift

58 lines
1.6 KiB
Swift
Raw Normal View History

2016-08-14 22:46:03 +03:00
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
2016-09-25 18:50:33 +03:00
func call(_ closure: @autoclosure () -> Void, when condition: Bool) { if condition { closure() } }
func call(_ closure: @autoclosure () -> Void, whenNot condition: Bool) { if !condition { closure() } }
extension String {
2016-09-25 18:50:33 +03:00
func without(prefix: String) -> String {
guard self.hasPrefix(prefix) else {
return self
}
2016-09-25 18:50:33 +03:00
let idx = self.characters.index(self.startIndex, offsetBy: prefix.characters.count)
return self[idx..<self.endIndex]
}
}
2016-09-11 15:59:17 +03:00
extension Array {
/// Concurrent and chunked version of `Array.map`.
///
/// - parameters:
/// - chunk: Batch size; defaults to `100`.
/// - queue: Defaults to `dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)`.
/// - transform: The transform function.
/// - returns: Transformed array of `self`.
func concurrentChunkMap<R>(
2016-09-25 18:50:33 +03:00
_ chunk: Int = 100,
queue: DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated),
2016-09-11 15:59:17 +03:00
transform: (Element) -> R) -> [R]
{
let count = self.count
let chunkedCount = Int(ceil(Float(count) / Float(chunk)))
var result: [[R]] = []
var spinLock = OS_SPINLOCK_INIT
2016-09-25 18:50:33 +03:00
DispatchQueue.concurrentPerform(iterations: chunkedCount) { idx in
let startIndex = Swift.min(idx * chunk, count)
let endIndex = Swift.min(startIndex + chunk, count)
2016-09-11 15:59:17 +03:00
let mappedChunk = self[startIndex..<endIndex].map(transform)
OSSpinLockLock(&spinLock)
result.append(mappedChunk)
OSSpinLockUnlock(&spinLock)
}
return result.flatMap { $0 }
}
2016-09-25 18:50:33 +03:00
}