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
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. | |
// This impl makes me sad. Lots of state and copies the entire collection twice (once during transforming, and once to unreverse) | |
extension Collection { | |
func mapExceptLast(matching predicate: (Element) -> Bool, transform: (Element) -> Element) -> [Element] { | |
var result: [Element] = [] | |
var found = false | |
for element in reversed() { | |
if !found && predicate(element) { | |
result.append(element) | |
found = true | |
} else { | |
result.append(transform(element)) | |
} | |
} | |
return Array(result.reversed()) | |
} | |
} | |
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
My attempt -> still copies twice though