Last active
October 31, 2022 16:50
-
-
Save DanielCardonaRojas/9aaf8bc689590c9c7cccbe213e6be9e6 to your computer and use it in GitHub Desktop.
FP Array Extensions
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
var str = "hhhhh Hello playground" | |
extension String { | |
static func groupBy(_ string: String, _ f: (Character, Character) -> Bool) -> [String] { | |
let array = Array(string) as! [Character] | |
let groups = Array.groupBy(array, f) | |
return groups.map { g in String(g) } | |
} | |
static func group(_ string: String) -> [String] { | |
return groupBy(string) { (leftChar, rightChar) in leftChar == rightChar } | |
} | |
} | |
extension Array { | |
static func groupBy(_ array: [Element] , _ f: (Element, Element) -> Bool) -> [[Element]] { | |
guard let firstChar = array.first else { | |
return [] | |
} | |
let (left, right) = Array.span(array, { c in f(firstChar, c) }) | |
return [left] + groupBy(right, f) | |
} | |
static func span(_ array: [Element], _ pred: (Element) -> Bool) -> ([Element], [Element]) { | |
if array.isEmpty { | |
return ([], []) | |
} | |
let right = Array(array.drop(while: pred)) | |
let left = Array(array.prefix(while: pred)) | |
return (left, right) | |
} | |
func groupBy(_ f: (Element, Element) -> Bool) -> [[Element]] { | |
return Array.groupBy(self, f) | |
} | |
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)}) | |
} | |
} | |
extension Array where Element: Equatable { | |
static func group(_ array: [Element]) -> [[Element]] { | |
return groupBy(array as! [Element]) { (leftElem, rightElem) in leftElem == rightElem } | |
} | |
func group() -> [[Element]] { | |
return Array.group(self) | |
} | |
} | |
let group = String.group(str) | |
print("Group string: \(group) \n") | |
let group1 = Array.group([1,2,5,5,5,6,7,7]) | |
print("Group array: \(group1)\n") | |
let span1 = Array.span([1,1,1,2,2,2], { e in e != 2} ) | |
print("Span array: \(span1)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment