Skip to content

Instantly share code, notes, and snippets.

@damodarnamala
Last active April 8, 2022 07:02
Show Gist options
  • Save damodarnamala/1b7573aaa9e2fb7ea1c2ec85507ed482 to your computer and use it in GitHub Desktop.
Save damodarnamala/1b7573aaa9e2fb7ea1c2ec85507ed482 to your computer and use it in GitHub Desktop.
Sequence Extension
extension Sequence {
public func inspect(_ body: (Element) throws -> Void) rethrows -> Self {
for element in self {
try body(element)
}
return self
}
}
extension Sequence {
func scan<Result>(
initialResult: Result,
_ nextPartialResult: (Result, Element) throws -> Result
) rethrows -> [Result] {
var iterator = makeIterator()
var results = ContiguousArray<Result>()
var accumulated: Result = initialResult
while let element = iterator.next() {
accumulated = try nextPartialResult(accumulated, element)
results.append(accumulated)
}
return Array(results)
}
}
// 1.
["C", "B", "A", "D"]
.sorted()
.inspect { (string) in
print("Inspecting: \(string)")
}.filter { (string) -> Bool in
string < "C"
}.forEach {
print("Result: \($0)")
}
// 2.
let results = (0..<5).scan(initialResult: "") { (result: String, int:
Int) -> String in
return "\(result)\(int)"
}
print(results) // ["0", "01", "012", "0123", "01234"]
let lowercased = ["S", "W", "I", "F", "T"].scan(initialResult: "") {
(result: String, string: String) -> String in
return "\(result)\(string.lowercased())"
}
print(lowercased) // ["s", "sw", "swi", "swif", "swift"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment