Created
February 28, 2018 08:25
-
-
Save ldrr/2258ca3ca87f06951b3dcda09ca8091b to your computer and use it in GitHub Desktop.
Neat extension for array delta
This file contains hidden or 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
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