Last active
November 22, 2018 01:03
-
-
Save commscheck/c9de0924c2dd8f6c96ad884eda0c04d9 to your computer and use it in GitHub Desktop.
Pad list of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Collection where Element == String { | |
func pad(to commonString: String) -> [String] { | |
let stringsAndWidths = self.map { string -> (String, Int) in | |
return (string, string[string.startIndex ..< string.range(of: commonString)!.lowerBound].count) | |
} | |
let marginWidth = stringsAndWidths.map { $0.1 }.reduce(0) { result, count -> Int in Swift.max(result, count) } | |
return stringsAndWidths.map { tuple -> String in | |
let (string, width) = tuple | |
return string.prefix(width).padding(toLength: marginWidth, withPad: " ", startingAt: 0) + tuple.0.suffix(tuple.0.count - tuple.1) | |
} | |
} | |
} | |
let input = """ | |
func foo() { return NSLocalizedString("foo", comment: "this is foo") } | |
func alphaBetaCharlie() { return NSLocalizedString("alpha beta charlie", comment: "this is alpha beta charlie") } | |
func alpha() { return NSLocalizedString("alpha", comment: "this is alpha") } | |
""" | |
let strings = input.split(separator: "\n").map { String($0) } | |
let fixed = strings | |
.pad(to: "{ return NSLocalizedString") | |
.pad(to: "comment: ") | |
for string in fixed { | |
print(string) | |
} | |
// Output: | |
// | |
// func foo() { return NSLocalizedString("foo", comment: "this is foo") } | |
// func alphaBetaCharlie() { return NSLocalizedString("alpha beta charlie", comment: "this is alpha beta charlie") } | |
// func alpha() { return NSLocalizedString("alpha", comment: "this is alpha") } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment