Created
March 8, 2018 16:05
-
-
Save natecook1000/45c3df2aa5f84a834063329a478c7972 to your computer and use it in GitHub Desktop.
This file contains 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 last(where predicate: (Element) throws -> Bool) rethrows -> Element? { | |
var result: Element? = nil | |
for el in self { | |
if try predicate(el) { | |
result = el | |
} | |
} | |
return result | |
} | |
} | |
extension Collection { | |
func lastIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? { | |
var result: Index? = nil | |
var i = startIndex | |
while i < endIndex { | |
if try predicate(self[i]) { | |
result = i | |
} | |
formIndex(after: &i) | |
} | |
return result | |
} | |
} | |
extension Collection where Element: Equatable { | |
func lastIndex(of element: Element) -> Index? { | |
return lastIndex(where: { $0 == element }) | |
} | |
} | |
extension BidirectionalCollection { | |
func last(where predicate: (Element) throws -> Bool) rethrows -> Element? { | |
var i = endIndex | |
while i > startIndex { | |
formIndex(before: &i) | |
if try predicate(self[i]) { | |
return self[i] | |
} | |
} | |
return nil | |
} | |
func lastIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? { | |
return try indices.last(where: { try predicate(self[$0]) }) | |
} | |
} | |
extension BidirectionalCollection where Element: Equatable { | |
func lastIndex(of element: Element) -> Index? { | |
return lastIndex(where: { $0 == element }) | |
} | |
} | |
let a = [20, 30, 10, 40, 20, 30, 10, 40, 20] | |
a.last(where: { $0 > 25 }) // 40 | |
a.lastIndex(where: { $0 > 25 }) // 7 | |
a.lastIndex(of: 10) // 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment