diff --git a/Sources/Algorithms/Chain.swift b/Sources/Algorithms/Chain.swift
index e8500aa..a7929b6 100644
--- a/Sources/Algorithms/Chain.swift
+++ b/Sources/Algorithms/Chain.swift
@@ -209,7 +209,20 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
}
}
- // TODO: Add distance(from:to:)
+ public func distance(from start: Index, to end: Index) -> Int {
+ switch (start.position, end.position) {
+ case let (.first(i), .first(j)):
+ return base1.distance(from: i, to: j)
+ case let (.second(i), .second(j)):
+ return base2.distance(from: i, to: j)
+ case let (.first(i), .second(j)):
+ return base1.distance(from: i, to: base1.endIndex)
+ + base2.distance(from: base2.startIndex, to: j)
+ case let (.second(i), .first(j)):
+ return base2.distance(from: i, to: base2.startIndex)
+ + base1.distance(from: base1.endIndex, to: j)
+ }
+ }
}
extension Chain: BidirectionalCollection
diff --git a/Tests/SwiftAlgorithmsTests/ChainTests.swift b/Tests/SwiftAlgorithmsTests/ChainTests.swift
index 3a1c1c9..1d36774 100644
--- a/Tests/SwiftAlgorithmsTests/ChainTests.swift
+++ b/Tests/SwiftAlgorithmsTests/ChainTests.swift
@@ -10,9 +10,17 @@
//===----------------------------------------------------------------------===//
import XCTest
-import Algorithms
+@testable import Algorithms
final class ChainTests: XCTestCase {
+ // intentionally does not depend on `Chain.index(_:offsetBy:)` in order to
+ // avoid making assumptions about the code being tested
+ func index(atOffset offset: Int, in chain: Chain) -> Chain.Index {
+ offset < chain.base1.count
+ ? .init(first: chain.base1.index(chain.base1.startIndex, offsetBy: offset))
+ : .init(second: chain.base2.index(chain.base2.startIndex, offsetBy: offset - chain.base1.count))
+ }
+
func testChainSequences() {
let run = (1...).prefix(10).chained(with: 20...)
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
@@ -35,5 +43,20 @@ final class ChainTests: XCTestCase {
XCTAssertEqualSequences(s1.reversed().chained(with: s2), "JIHGFEDCBAklmnopqrstuv")
}
- // TODO: Add tests that check distance and index(offsetBy:)
+ // TODO: Add tests that check index(offsetBy:)
+
+ func testChainDistanceFromTo() {
+ let s1 = "abcde"
+ let s2 = "VWXYZ"
+ let chain = s1.chained(with: s2)
+
+ XCTAssertEqual(chain.count, s1.count + s2.count)
+
+ for (startOffset, endOffset) in product(0...chain.count, 0...chain.count) {
+ let start = index(atOffset: startOffset, in: chain)
+ let end = index(atOffset: endOffset, in: chain)
+ let distance = endOffset - startOffset
+ XCTAssertEqual(chain.distance(from: start, to: end), distance)
+ }
+ }
}