Skip to content

add suffix:while method #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 9, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions Sources/Algorithms/Suffix.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand All @@ -14,18 +14,17 @@
//===----------------------------------------------------------------------===//

extension BidirectionalCollection {
@inlinable
public __consuming func Suffix(while predicate: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()
self.reverse()
for element in self {
guard try predicate(element) else {
break
}
result.append(element)
public func suffix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
let start = startIndex
var result = endIndex
while result != start {
let previous = index(before: result)
guard try predicate(self[previous]) else { break }

result = previous
}
result.reverse()
return Array(result)
return self[result...]
}
}
}
7 changes: 6 additions & 1 deletion Tests/SwiftAlgorithmsTests/SuffixTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand All @@ -17,4 +17,9 @@ final class SuffixTests: XCTestCase {
func testSuffix() {
let a = 0...10
XCTAssertEqualSequences(a.suffix(while: { $0 > 5 }), (6...10))
XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [9])
XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
let empty = (0...).prefix(0)
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
}