Last active
January 9, 2018 06:30
-
-
Save kakajika/c2b37eb1b669224dd078e29f671c1a36 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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