Last active
March 27, 2021 01:08
-
-
Save DanielCardonaRojas/fb5d9fd6c6094b5531f8fb98b8fa3f94 to your computer and use it in GitHub Desktop.
More Array Extensions flattened, unwrapped, all and any.
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
extension Array { | |
func flattened<T>() -> [T] where Element == [T] { | |
return self.flatMap({ $0 }) | |
} | |
func all(_ pred: (Element) -> Bool) -> Bool { | |
return self.reduce(true, { acc, v in acc && pred(v) }) | |
} | |
func any(_ pred: (Element) -> Bool) -> Bool { | |
return self.reduce(false, { acc, v in acc || pred(v) }) | |
} | |
subscript(safe index: Int) -> Element? { | |
guard index < self.count && index >= 0 else { | |
return nil | |
} | |
return self[index] | |
} | |
} | |
extension Array { | |
func groupBy(_ f: (Element, Element) -> Bool) -> [[Element]] { | |
guard let firstElement = first else { | |
return [] | |
} | |
return reduce(into: [[]], { acc, next in | |
guard let lastGroup = acc.last else { | |
acc.append([next]) | |
return | |
} | |
let previous = lastGroup.last ?? firstElement | |
if f(previous, next) { | |
var previousGroup = lastGroup | |
previousGroup.append(next) | |
let count = acc.count | |
acc[count - 1] = previousGroup | |
} else { | |
acc.append([next]) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment