From da475ea9af0052b65f9958dbc5d33a2c40c8ec23 Mon Sep 17 00:00:00 2001 From: Matt Zanchelli Date: Thu, 16 Dec 2021 08:10:17 -0500 Subject: [PATCH] Clarify `endIndex` behavior of `partitioningIndex(where:)` in documentation (Resolves #170) (#171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The returned index isn’t necessarily an index of an element. In the case where it returns `endIndex`, it’s not valid for subscripting the collection. --- Sources/Algorithms/Partition.swift | 7 ++++--- .../SwiftAlgorithmsTests/PartitionTests.swift | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Sources/Algorithms/Partition.swift b/Sources/Algorithms/Partition.swift index 5081bc3..178bd4c 100644 --- a/Sources/Algorithms/Partition.swift +++ b/Sources/Algorithms/Partition.swift @@ -168,8 +168,8 @@ extension MutableCollection where Self: BidirectionalCollection { //===----------------------------------------------------------------------===// extension Collection { - /// Returns the index of the first element in the collection that matches - /// the predicate. + /// Returns the start index of the partition of a collection that matches + /// the given predicate. /// /// The collection must already be partitioned according to the predicate. /// That is, there should be an index `i` where for every element in @@ -179,7 +179,8 @@ extension Collection { /// - Parameter belongsInSecondPartition: A predicate that partitions the /// collection. /// - Returns: The index of the first element in the collection for which - /// `predicate` returns `true`. + /// `predicate` returns `true`, or `endIndex` if there are no elements + /// for which `predicate` returns `true`. /// /// - Complexity: O(log *n*), where *n* is the length of this collection if /// the collection conforms to `RandomAccessCollection`, otherwise O(*n*). diff --git a/Tests/SwiftAlgorithmsTests/PartitionTests.swift b/Tests/SwiftAlgorithmsTests/PartitionTests.swift index 49bb867..6dd4a8f 100644 --- a/Tests/SwiftAlgorithmsTests/PartitionTests.swift +++ b/Tests/SwiftAlgorithmsTests/PartitionTests.swift @@ -92,6 +92,26 @@ final class PartitionTests: XCTestCase { } } + func testPartitioningIndexWithEmptyInput() { + let input: [Int] = [] + + let a = input.partitioningIndex(where: { _ in return true }) + XCTAssertEqual(a, input.startIndex) + + let b = input.partitioningIndex(where: { _ in return false }) + XCTAssertEqual(b, input.endIndex) + } + + func testPartitioningIndexWithOneEmptyPartition() { + let input: Range = (0 ..< 10) + + let a = input.partitioningIndex(where: { $0 > 10 }) + XCTAssertEqual(a, input.endIndex) + + let b = input.partitioningIndex(where: { $0 >= 0 }) + XCTAssertEqual(b, input.startIndex) + } + func testPartitionWithSubrangeBidirectionalCollection() { for length in 10...20 { let a = Array(0..