Last active
May 17, 2018 15:24
-
-
Save marcosgriselli/f4fab6738f2da8abc8e21b9fee1a3d0d to your computer and use it in GitHub Desktop.
Array utility functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// MARK: - Array | |
public extension Array { | |
/// Safe subscript for element at index | |
/// | |
/// - Parameter index: array's index to subscript. | |
/// - Returns: Optional array element if it exists in that index. | |
public func item(at index: Int) -> Element? { | |
guard count > index else { return nil } | |
guard index >= 0 else { return nil } | |
return self[index] | |
} | |
/// Picks random elements from the array. Accepts duplicates. | |
/// | |
/// - Parameter amount: elements count to be picked randomly. | |
public subscript (randomPick amount: Int) -> [Element] { | |
var random = [Element]() | |
for _ in 0..<amount { | |
let indexToSelect = Int(arc4random_uniform(UInt32(count - 1))) | |
let element = self[indexToSelect] | |
random.append(element) | |
} | |
return random | |
} | |
/// Keeps the last 'n' items in the array. | |
/// | |
/// - Parameters: | |
/// - maxCount: maximum amount of elements the array should keep. | |
public func keepLast(_ maxCount: Int) -> Array { | |
return Array(suffix(maxCount)) | |
} | |
/// Generates a new array with a shifted starting point. | |
/// | |
/// - Parameter positions: Amount of elements to shift. | |
/// - Returns: New array with shifted elements. | |
public func shifted(_ positions: Int) -> Array { | |
var result = self[positions..<self.count] | |
result += self[0..<positions] | |
return Array(result) | |
} | |
/// Splits the array in multiple arrays. | |
/// | |
/// - Parameter size: Size of the sub arrays | |
/// - Returns: Array of Arrays. | |
public func chunks(size: Int) -> [[Element]] { | |
return stride(from: 0, to: count, by: size).map { | |
let range = $0..<Swift.min($0 + size, count) | |
return Array(self[range]) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment