File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
Tests/SwiftAlgorithmsTests Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ //===----------------------------------------------------------------------===//
2+ //
3+ // This source file is part of the Swift Algorithms open source project
4+ //
5+ // Copyright (c) 2021 Apple Inc. and the Swift project authors
6+ // Licensed under Apache License v2.0 with Runtime Library Exception
7+ //
8+ // See https://swift.org/LICENSE.txt for license information
9+ //
10+ //===----------------------------------------------------------------------===//
11+
12+ //===----------------------------------------------------------------------===//
13+ // Suffix(while:)
14+ //===----------------------------------------------------------------------===//
15+
16+ extension BidirectionalCollection {
17+ /// Returns a subsequence containing the elements from the end until
18+ /// `predicate` returns `false` and skipping the remaining elements.
19+ ///
20+ /// - Parameter predicate: A closure that takes an element of the
21+ /// sequence as its argument and returns `true` if the element should
22+ /// be included or `false` if it should be excluded. Once the predicate
23+ /// returns `false` it will not be called again.
24+ ///
25+ /// - Complexity: O(*n*), where *n* is the length of the collection.
26+ public func suffix(
27+ while predicate: ( Element ) throws -> Bool
28+ ) rethrows -> SubSequence {
29+ let start = startIndex
30+ var result = endIndex
31+ while result != start {
32+ let previous = index ( before: result)
33+ guard try predicate ( self [ previous] ) else { break }
34+ result = previous
35+ }
36+ return self [ result... ]
37+ }
38+ }
Original file line number Diff line number Diff line change 1+ //===----------------------------------------------------------------------===//
2+ //
3+ // This source file is part of the Swift Algorithms open source project
4+ //
5+ // Copyright (c) 2021 Apple Inc. and the Swift project authors
6+ // Licensed under Apache License v2.0 with Runtime Library Exception
7+ //
8+ // See https://swift.org/LICENSE.txt for license information
9+ //
10+ //===----------------------------------------------------------------------===//
11+
12+ import XCTest
13+ import Algorithms
14+
15+ final class SuffixTests : XCTestCase {
16+ func testSuffix( ) {
17+ let a = 0 ... 10
18+ XCTAssertEqualSequences ( a. suffix ( while: { $0 > 5 } ) , ( 6 ... 10 ) )
19+ XCTAssertEqualSequences ( a. suffix ( while: { $0 > 10 } ) , [ ] )
20+ XCTAssertEqualSequences ( a. suffix ( while: { $0 > 9 } ) , [ 10 ] )
21+ XCTAssertEqualSequences ( a. suffix ( while: { $0 > - 1 } ) , ( 0 ... 10 ) )
22+
23+ let empty : [ Int ] = [ ]
24+ XCTAssertEqualSequences ( empty. suffix ( while: { $0 > 10 } ) , [ ] )
25+ }
26+ }
You can’t perform that action at this time.
0 commit comments