From 813ea7905e87457ac7ddd5d6bbc1bba6f5a2750c Mon Sep 17 00:00:00 2001 From: michiboo Date: Fri, 22 Jan 2021 16:17:28 +0200 Subject: [PATCH] add more test for suffix Tests --- Sources/Algorithms/Suffix.swift | 27 ++++++++++---------- Tests/SwiftAlgorithmsTests/SuffixTests.swift | 7 ++++- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/Sources/Algorithms/Suffix.swift b/Sources/Algorithms/Suffix.swift index 7ea18b5..1cc10ac 100644 --- a/Sources/Algorithms/Suffix.swift +++ b/Sources/Algorithms/Suffix.swift @@ -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 @@ -14,18 +14,17 @@ //===----------------------------------------------------------------------===// extension BidirectionalCollection { - @inlinable - public __consuming func Suffix(while predicate: (Element) throws -> Bool - ) rethrows -> [Element] { - var result = ContiguousArray() - 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...] } -} +} \ No newline at end of file diff --git a/Tests/SwiftAlgorithmsTests/SuffixTests.swift b/Tests/SwiftAlgorithmsTests/SuffixTests.swift index 3d9827c..8687639 100644 --- a/Tests/SwiftAlgorithmsTests/SuffixTests.swift +++ b/Tests/SwiftAlgorithmsTests/SuffixTests.swift @@ -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 @@ -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 }), []) }