Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created March 8, 2018 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natecook1000/45c3df2aa5f84a834063329a478c7972 to your computer and use it in GitHub Desktop.
Save natecook1000/45c3df2aa5f84a834063329a478c7972 to your computer and use it in GitHub Desktop.
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