Last active
October 23, 2020 15:04
-
-
Save khanlou/dbbf7e5a87058b6a3b7af76be0166940 to your computer and use it in GitHub Desktop.
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 Sequence { | |
func eachPair() -> Zip2Sequence<Self, DropFirstSequence<Self>> { | |
return zip(self, self.dropFirst()) | |
} | |
} | |
extension Collection { | |
func indexed() -> [(index: Index, element: Element)] { | |
return zip(indices, self).map({ (index: $0, element: $1) }) | |
} | |
func slice(between predicate: (Element, Element) -> Bool) -> [SubSequence] { | |
let innerSlicingPoints = self | |
.indexed() | |
.eachPair() | |
.filter({ predicate($0.0.element, $0.1.element) }) | |
.lazy | |
.map({ $0.1.index }) | |
let slicingPoints = [self.startIndex] + innerSlicingPoints + [self.endIndex] | |
return slicingPoints | |
.eachPair() | |
.map({ self[$0..<$1] }) | |
} | |
func slice(before predicate: (Element) -> Bool) -> [SubSequence] { | |
return self.slice(between: { left, right in | |
return predicate(right) | |
}) | |
} | |
func slice(after predicate: (Element) -> Bool) -> [SubSequence] { | |
return self.slice(between: { left, right in | |
return predicate(left) | |
}) | |
} | |
} | |
let a = [1, 1, 2, 3, 3, 2, 3, 3, 4] | |
a.slice(between: !=) | |
let string1 = "AsdafTalk" | |
let b = string1.slice(before: { ("A"..."Z").contains($0) }).map({ String($0) }) | |
b | |
let string2 = "slice.period." | |
let c = string2.slice(after: { $0 == "." }).map({ String($0) }) | |
c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment