extension RangeReplaceableCollection where Self: StringProtocol {
func paddingToLeft(upTo length: Int, using element: Element = " ") -> SubSequence {
return repeatElement(element, count: Swift.max(0, length-count)) + suffix(Swift.max(count, count-length))
}
}
"123".paddingToLeft(upTo: 5) // " 123"
"123".paddingToLeft(upTo: 5, using: "0") // "00123"
"123".paddingToLeft(upTo: 3, using: "0") // "123"
"$199.99".dropLast(3).paddingToLeft(upTo: 10, using: "_") // "______$199"
To replicate the same behaviour as padding(toLength:, withPad:, startingAt:)
we can add rotateTo left functionality to RangeReplaceableCollection
extension RangeReplaceableCollection {
func rotatingLeft(positions: Int) -> SubSequence {
let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex
return self[index...] + self[..<index]
}
}
And implement it as follow:
extension RangeReplaceableCollection where Self: StringProtocol {
func paddingToLeft<S: StringProtocol & RangeReplaceableCollection>(upTo length: Int, with string: S, startingAt index: Int = 0) -> SubSequence {
let string = string.rotatingLeft(positions: index)
return repeatElement(string, count: length-count/string.count)
.joined().prefix(length-count) + suffix(Swift.max(count, count-length))
}
}
"123".paddingToLeft(upTo: 10, with: "abc", startingAt: 2) // "cabcabc123"
"123".padding(toLength: 10, withPad: "abc", startingAt: 2) // "123cabcabc"