Skip to content

Commit 14d88f7

Browse files
committed
Add Array CC_padded(to:with:) and unit tests
1 parent e1d35cb commit 14d88f7

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//
2+
// Cornucopia – (C) Dr. Lauer Information Technology
3+
//
4+
public extension Array {
5+
6+
/// Returns a copy padded to at least the requested `length` using `element`.
7+
func CC_padded(to length: Int, with element: Element) -> [Element] {
8+
guard length > count else { return self }
9+
return self + Array(repeating: element, count: length - count)
10+
}
11+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import XCTest
2+
3+
import CornucopiaCore
4+
5+
class ArrayPaddingTests: XCTestCase {
6+
7+
func testCC_paddedAddsElements() {
8+
let given: [UInt8] = [0x01, 0x02]
9+
let when = given.CC_padded(to: 4, with: 0xFF)
10+
let expected: [UInt8] = [0x01, 0x02, 0xFF, 0xFF]
11+
XCTAssertEqual(when, expected)
12+
}
13+
14+
func testCC_paddedNoopWhenAlreadyLonger() {
15+
let given = [1, 2, 3]
16+
let when = given.CC_padded(to: 2, with: 0)
17+
XCTAssertEqual(when, given)
18+
}
19+
20+
func testCC_paddedNoopWhenExactLength() {
21+
let given = ["a", "b"]
22+
let when = given.CC_padded(to: 2, with: "z")
23+
XCTAssertEqual(when, given)
24+
}
25+
26+
func testCC_paddedEmptyArray() {
27+
let given: [Int] = []
28+
let when = given.CC_padded(to: 3, with: 7)
29+
XCTAssertEqual(when, [7, 7, 7])
30+
}
31+
32+
func testCC_paddedNegativeLengthNoop() {
33+
let given = [1, 2]
34+
let when = given.CC_padded(to: -1, with: 9)
35+
XCTAssertEqual(when, given)
36+
}
37+
}

0 commit comments

Comments
 (0)