Skip to content

Commit 813ea79

Browse files
committed
add more test for suffix Tests
1 parent 1acc213 commit 813ea79

File tree

2 files changed

+19
-15
lines changed

2 files changed

+19
-15
lines changed

Sources/Algorithms/Suffix.swift

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//
33
// This source file is part of the Swift Algorithms open source project
44
//
5-
// Copyright (c) 2020 Apple Inc. and the Swift project authors
5+
// Copyright (c) 2021 Apple Inc. and the Swift project authors
66
// Licensed under Apache License v2.0 with Runtime Library Exception
77
//
88
// See https://swift.org/LICENSE.txt for license information
@@ -14,18 +14,17 @@
1414
//===----------------------------------------------------------------------===//
1515

1616
extension BidirectionalCollection {
17-
@inlinable
18-
public __consuming func Suffix(while predicate: (Element) throws -> Bool
19-
) rethrows -> [Element] {
20-
var result = ContiguousArray<Element>()
21-
self.reverse()
22-
for element in self {
23-
guard try predicate(element) else {
24-
break
25-
}
26-
result.append(element)
17+
public func suffix(
18+
while predicate: (Element) throws -> Bool
19+
) rethrows -> SubSequence {
20+
let start = startIndex
21+
var result = endIndex
22+
while result != start {
23+
let previous = index(before: result)
24+
guard try predicate(self[previous]) else { break }
25+
26+
result = previous
2727
}
28-
result.reverse()
29-
return Array(result)
28+
return self[result...]
3029
}
31-
}
30+
}

Tests/SwiftAlgorithmsTests/SuffixTests.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//
33
// This source file is part of the Swift Algorithms open source project
44
//
5-
// Copyright (c) 2020 Apple Inc. and the Swift project authors
5+
// Copyright (c) 2021 Apple Inc. and the Swift project authors
66
// Licensed under Apache License v2.0 with Runtime Library Exception
77
//
88
// See https://swift.org/LICENSE.txt for license information
@@ -17,4 +17,9 @@ final class SuffixTests: XCTestCase {
1717
func testSuffix() {
1818
let a = 0...10
1919
XCTAssertEqualSequences(a.suffix(while: { $0 > 5 }), (6...10))
20+
XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
21+
XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [9])
22+
XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
23+
let empty = (0...).prefix(0)
24+
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
2025
}

0 commit comments

Comments
 (0)