File tree Expand file tree Collapse file tree 2 files changed +19
-15
lines changed
Tests/SwiftAlgorithmsTests Expand file tree Collapse file tree 2 files changed +19
-15
lines changed Original file line number Diff line number Diff line change 2
2
//
3
3
// This source file is part of the Swift Algorithms open source project
4
4
//
5
- // Copyright (c) 2020 Apple Inc. and the Swift project authors
5
+ // Copyright (c) 2021 Apple Inc. and the Swift project authors
6
6
// Licensed under Apache License v2.0 with Runtime Library Exception
7
7
//
8
8
// See https://swift.org/LICENSE.txt for license information
14
14
//===----------------------------------------------------------------------===//
15
15
16
16
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
27
27
}
28
- result. reverse ( )
29
- return Array ( result)
28
+ return self [ result... ]
30
29
}
31
- }
30
+ }
Original file line number Diff line number Diff line change 2
2
//
3
3
// This source file is part of the Swift Algorithms open source project
4
4
//
5
- // Copyright (c) 2020 Apple Inc. and the Swift project authors
5
+ // Copyright (c) 2021 Apple Inc. and the Swift project authors
6
6
// Licensed under Apache License v2.0 with Runtime Library Exception
7
7
//
8
8
// See https://swift.org/LICENSE.txt for license information
@@ -17,4 +17,9 @@ final class SuffixTests: XCTestCase {
17
17
func testSuffix( ) {
18
18
let a = 0 ... 10
19
19
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 } ) , [ ] )
20
25
}
You can’t perform that action at this time.
0 commit comments