Created
August 4, 2014 23:49
-
-
Save GarthSnyder/551a1574dbea2c219fe9 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
#!/usr/bin/env xcrun swift | |
// Garth Snyder - August 4, 2014 | |
struct TakeWhile<T: SequenceType> : SequenceType | |
{ | |
typealias Element = T.Generator.Element | |
let underlyingSequence: T | |
let keepGoing: Element -> Bool | |
init(_ underlyingSequence: T, _ keepGoing: Element -> Bool) { | |
self.underlyingSequence = underlyingSequence | |
self.keepGoing = keepGoing | |
} | |
func generate() -> GeneratorOf<Element> { | |
var underlyingGenerator = underlyingSequence.generate() | |
return GeneratorOf<Element> { | |
if let candidate = underlyingGenerator.next() { | |
if self.keepGoing(candidate) { | |
return candidate | |
} | |
} | |
return nil | |
} | |
} | |
} | |
var array = Array(TakeWhile([1, 2, 3, 4]) {$0 < 3}) | |
println(array) | |
// Also allow takeWhile as a method on Array | |
extension Array { | |
func takeWhile(keepGoing: T -> Bool) -> TakeWhile<Array> { | |
return TakeWhile(self, keepGoing) | |
} | |
} | |
var anotherArray = Array([1, 2, 3, 4].takeWhile {$0 < 3}) | |
println(anotherArray) | |
// More tests from practicalswift | |
assert(equal([1, 2, 3, 4, 3, 2, 1].takeWhile { $0 < 3 }, [1, 2])) | |
assert(equal(["a", "b", "c", "d", "c", "b", "a"].takeWhile { $0 < "d" }, ["a", "b", "c"])) | |
assert(equal([1.1, 2.2, 3.3, 4.4, 3.3, 2.2, 1.1].takeWhile { $0 < 3 }, [1.1, 2.2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment