Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Forked from rnapier/mapExceptLast.swift
Last active May 30, 2018 19:39
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/9d2a7130f6f3a394ebe5fa9e28482e4e to your computer and use it in GitHub Desktop.
Save natecook1000/9d2a7130f6f3a394ebe5fa9e28482e4e to your computer and use it in GitHub Desktop.
let xs = [0,1,2,3,4,5]
let double: (Int) -> Int = { $0 * 2 }
let isEven: (Int) -> Bool = { $0 % 2 == 0 }
// Goal: [0,2,4,6,4,10]. Double all but the last even element.
extension Collection {
func mapExceptLast(matching predicate: (Element) -> Bool, transform: (Element) -> Element) -> [Element] {
var result: [Element] = []
var lastMatch: (Element, Int)?
for element in self {
if predicate(element) {
lastMatch = (element, result.count)
}
result.append(transform(element))
}
// If we found a match, replace the last with untransformed element
if let (element, i) = lastMatch {
result[i] = element
}
return result
}
}
print(xs.mapExceptLast(matching: isEven, transform: double))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment