Can you think of a reason the following extension should not be used in production, or a better way of implementing it:
public extension Range {
@warn_unused_result
public func intersect(other: Range) -> Range {
let ds = startIndex.distanceTo(other.startIndex)
let de = startIndex.distanceTo(other.endIndex)
let s = ds <= 0 ? startIndex : startIndex.advancedBy(ds, limit: endIndex)
let e = de <= 0 ? startIndex : startIndex.advancedBy(de, limit: endIndex)
return s..<e
}
}
The method should pass the following assertions:
(5...7).intersect(9...9) == (8..<8) // ....|||.---..
(5...7).intersect(1...3) == (5..<5) // ....---.|||..
(5...7).intersect(8...9) == (8..<8) // ....|||---...
(5...7).intersect(1...4) == (5..<5) // ....---|||...
(5...7).intersect(7...9) == (7..<8) // ....||+--....
(5...7).intersect(1...5) == (5..<6) // ....--+||....
(5...7).intersect(6...9) == (6..<8) // ....|++-.....
(5...7).intersect(1...6) == (5..<7) // ....-++|.....
(5...7).intersect(6...6) == (6..<7) // ....|+|......
(5...7).intersect(4...8) == (5..<8) // ....-+++-....
Note the first four assertions with an empty intersection: the method is currently returning startIndex..<startIndex
if the other
range is on the "left", or endIndex..<endIndex
if it is on the "right". Is this a reasonable behaviour?