Skip to content

Instantly share code, notes, and snippets.

@kakajika
Last active January 9, 2018 06:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakajika/c2b37eb1b669224dd078e29f671c1a36 to your computer and use it in GitHub Desktop.
Save kakajika/c2b37eb1b669224dd078e29f671c1a36 to your computer and use it in GitHub Desktop.
extension Unicode.Scalar {
var width: UInt32 {
let code = self.value
if (code >= 0 && code <= 128) {
return 1
} else {
return 2
}
}
}
extension Character {
var width: UInt32 {
return self.unicodeScalars.reduce(0) { $0 + $1.width }
}
}
extension String {
var width: UInt32 {
return self.unicodeScalars.reduce(0) { $0 + $1.width }
}
}
let LINE_WIDTH_MAX = 30
let original = "あいうえおかきくけこさしすせそはひふへほ\nsasisusesoたちつてと"
let result: String = original
.split(separator: "\n")
.flatMap { line in
return line.reduce(into: [""], { (splitted, char) in
if var last = splitted.last, last.width + char.width <= LINE_WIDTH_MAX {
last.append(char)
splitted[splitted.count - 1] = last
} else {
splitted.append(String(char))
}
})
}
.prefix(3)
.joined(separator: "\n")
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment