Skip to content

Instantly share code, notes, and snippets.

@ldrr
Created February 28, 2018 08:25
Show Gist options
  • Save ldrr/2258ca3ca87f06951b3dcda09ca8091b to your computer and use it in GitHub Desktop.
Save ldrr/2258ca3ca87f06951b3dcda09ca8091b to your computer and use it in GitHub Desktop.
Neat extension for array delta
extension Array {
public func reduceDelta<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element, Element) throws -> Result) rethrows -> Result {
guard var previous = first else {
return initialResult
}
return try dropFirst().reduce(initialResult, { result, element in
let nextResult = try nextPartialResult(result, previous, element)
previous = element
return nextResult
})
}
}
// TESTS
class ArrayTests: XCTestCase {
func testReduceDelta() {
let testArray = [1, 2, 4, 10]
let delta = testArray.reduceDelta(0, { result, previous, current in
return result + current - previous
})
XCTAssertEqual(delta, 9)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment