mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Add a joined method with prefix/suffix
Joining with a prefix and suffix is a relatively common operation that isn't terribly simple to implement concisely. This adds that operation for joining strings. Related to #195.
This commit is contained in:
1 parent
288d8b00f2
commit
4b80f3eedd
2 files changed
+59
No files matched your search
@@ -487,3 +487,13 @@ extension LazySequenceProtocol where Elements: Collection, Element: Collection {
|
||||
JoinedByClosureCollection(base: elements, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element: Collection, Element.SubSequence == Substring {
|
||||
public func joined(separator: Element, prefix: Element, suffix: Element) -> String {
|
||||
var result = ""
|
||||
result.append(contentsOf: prefix[...])
|
||||
result.append(contentsOf: self.joined(separator: separator[...]))
|
||||
result.append(contentsOf: suffix[...])
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -129,4 +129,53 @@ final class JoinedTests: XCTestCase {
|
||||
validator2.validate(strings.lazy.joined(by: { _, _ in separator }))
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedPrefixSuffix() {
|
||||
let input = [
|
||||
[5,3,0, 0,7,0, 0,0,0],
|
||||
[6,0,0, 1,9,5, 0,0,0],
|
||||
[0,9,8, 0,0,0, 0,6,0],
|
||||
|
||||
[8,0,0, 0,6,0, 0,0,3],
|
||||
[4,0,0, 8,0,3, 0,0,1],
|
||||
[7,0,0, 0,2,0, 0,0,6],
|
||||
|
||||
[0,6,0, 0,0,0, 2,8,0],
|
||||
[0,0,0, 4,1,9, 0,0,5],
|
||||
[0,0,0, 0,8,0, 0,7,9],
|
||||
]
|
||||
|
||||
func prettyString(_ sudoku: [[Int]]) -> String {
|
||||
sudoku.chunks(ofCount: 3).map { (bigChunk: ArraySlice<[Int]>) -> String in
|
||||
bigChunk.map { (row: [Int]) -> String in
|
||||
row.chunks(ofCount: 3).map { (smallChunk: ArraySlice<Int>) -> String in
|
||||
smallChunk.lazy.map(String.init).joined(separator: " ", prefix: " ", suffix: " ")
|
||||
}.joined(separator: "|", prefix: "|", suffix: "|")
|
||||
}.joined(separator: "\n")
|
||||
}.joined(
|
||||
separator: "\n+-------+-------+-------+\n",
|
||||
prefix: "+-------+-------+-------+\n",
|
||||
suffix: "\n+-------+-------+-------+")
|
||||
}
|
||||
|
||||
let output = prettyString(input)
|
||||
XCTAssertEqual(
|
||||
output,
|
||||
"""
|
||||
+-------+-------+-------+
|
||||
| 5 3 0 | 0 7 0 | 0 0 0 |
|
||||
| 6 0 0 | 1 9 5 | 0 0 0 |
|
||||
| 0 9 8 | 0 0 0 | 0 6 0 |
|
||||
+-------+-------+-------+
|
||||
| 8 0 0 | 0 6 0 | 0 0 3 |
|
||||
| 4 0 0 | 8 0 3 | 0 0 1 |
|
||||
| 7 0 0 | 0 2 0 | 0 0 6 |
|
||||
+-------+-------+-------+
|
||||
| 0 6 0 | 0 0 0 | 2 8 0 |
|
||||
| 0 0 0 | 4 1 9 | 0 0 5 |
|
||||
| 0 0 0 | 0 8 0 | 0 7 9 |
|
||||
+-------+-------+-------+
|
||||
"""
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user