-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtextwrap.go
77 lines (72 loc) · 1.96 KB
/
textwrap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// TextWrap - A package made to simplify formatting text in a size limited space.
// Package textwrap does the main part of formatting the string
package textwrap
import (
"fmt"
"strings"
)
const (
// defaultDelim is the default seperator between words
defaultDelim string = " "
// defaultEnd is the default end of line
defaultEnd string = "\n"
)
// WrapCustom is the main function of the repo
// Given an input, and desired size
func WrapCustom(input string, size int, delim, end string) ([]string, error) {
if size < 1 {
return nil, fmt.Errorf("size should be larget than 0")
}
if len(delim) >= size {
return nil, fmt.Errorf("delimeter length bigger than size")
}
var results = []string{}
// Splitting according to line ending
var strs = strings.Split(input, end)
for _, str := range strs {
// If a line fits inside the size, add it whole
if len(str) <= size {
results = append(results, str)
continue
}
var curStr string
words := strings.Split(str, delim)
// Working on the words, word by word
for _, word := range words {
if len(curStr)+len(delim)+len(word) > size {
// If the next word doesn't fit
if curStr != "" {
// If the current string isn't empty, add it to results
results = append(results, curStr)
}
// Split up the next word until it fits
for len(word) > size {
results = append(results, word[:size])
word = word[size:]
}
curStr = word
} else {
// If the next word does fit, add it to the current string
if curStr == "" {
curStr = word
} else {
curStr += delim + word
}
}
}
// Add the rest
if curStr != "" {
results = append(results, curStr)
}
}
return results, nil
}
// Wrap calls WrapCustom with default paramets
// And returns the output joined by the line ending.
func Wrap(input string, size int) (string, error) {
res, err := WrapCustom(input, size, defaultDelim, defaultEnd)
if err != nil {
return "", err
}
return strings.Join(res, "\n"), nil
}