Skip to content

Commit 7c5f95c

Browse files
committed
Add Array/appending(_:) and Array/appending(contentsOf:)
1 parent 1398211 commit 7c5f95c

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Sources/Extensions/Array/Array+Selectors.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,32 @@ public extension Array where Element: Equatable {
4444
let erasedObject = object as AnyObject?
4545
return self.filter { $0 as AnyObject? !== erasedObject }
4646
}
47+
48+
/// Returns a new array with the specified element appended to the end.
49+
///
50+
/// - Parameter element: The element to append.
51+
/// - Returns: A new array containing all elements of the original array followed by the appended element.
52+
/// - Complexity: `O(n + 1)`, where n is the length of the original array.
53+
func appending(_ element: Element) -> [Element] {
54+
var arr = [Element]()
55+
arr.reserveCapacity(self.count + 1)
56+
arr.append(contentsOf: self)
57+
arr.append(element)
58+
return arr
59+
}
60+
61+
/// Returns a new array with the specified elements appended to the end.
62+
///
63+
/// - Parameter element: The element to append.
64+
/// - Returns: A new array containing all elements of the original array followed by the appended elements.
65+
/// - Complexity: `O(n + m)`, where n is the length of the original array and m is the length of the contents array.
66+
func appending(contentsOf contents: [Element]) -> [Element] {
67+
var arr = [Element]()
68+
arr.reserveCapacity(self.count + contents.count)
69+
arr.append(contentsOf: self)
70+
arr.append(contentsOf: contents)
71+
return arr
72+
}
4773
}
4874

4975
public extension Array where Element: Hashable {

Tests/Extensions/ArrayTests.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,16 @@ final class ArrayTests: XCTestCase {
228228
subject.move(fromOffset: 0, toOffset: 0)
229229
XCTAssertEqual(subject, [0])
230230
}
231+
232+
func testAppendingElement() {
233+
XCTAssertEqual([Int]().appending(1).appending(2), [1, 2])
234+
XCTAssertEqual([1].appending(2).appending(3), [1, 2, 3])
235+
}
236+
237+
func testAppendingElements() {
238+
XCTAssertEqual([Int]().appending(contentsOf: [Int]()), [Int]())
239+
XCTAssertEqual([Int]().appending(contentsOf: [1, 2]), [1, 2])
240+
XCTAssertEqual([1].appending(contentsOf: [2, 3]), [1, 2, 3])
241+
XCTAssertEqual([1, 2].appending(contentsOf: [Int]()), [1, 2])
242+
}
231243
}

0 commit comments

Comments
 (0)