Last active
March 22, 2017 17:41
-
-
Save vancluever/7ce88b801205c1731378f66c327d877e to your computer and use it in GitHub Desktop.
GoLang Kata WordWrap (Non-Unicode) - https://play.golang.org/p/zu9k0qjUzU
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
package main | |
import ( | |
"bytes" | |
"fmt" | |
) | |
const in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." | |
func wrap(old string, ll int) string { | |
var word, space, line, new bytes.Buffer | |
for _, c := range old { | |
switch c { | |
case ' ', '\n': | |
if word.Len() > 0 { | |
space.WriteTo(&line) | |
word.WriteTo(&line) | |
space.Reset() | |
word.Reset() | |
} | |
space.WriteRune(' ') | |
default: | |
if line.Len()+space.Len()+word.Len() >= ll { | |
space.Reset() | |
line.WriteRune('\n') | |
line.WriteTo(&new) | |
line.Reset() | |
} | |
word.WriteRune(c) | |
} | |
} | |
// write out last line | |
if word.Len() > 0 { | |
space.WriteTo(&line) | |
word.WriteTo(&line) | |
} | |
line.WriteTo(&new) | |
return new.String() | |
} | |
func main() { | |
fmt.Println(wrap(in, 40)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment