Skip to content

Commit

Permalink
Add functions for prefix and suffix detection
Browse files Browse the repository at this point in the history
  • Loading branch information
xyproto committed Feb 11, 2019
1 parent 2aa2008 commit 775bba9
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ import (
"os/exec"
"path/filepath"
"strings"
"time"
)

// c formats a timestamp as HH:MM
func c(t time.Time) string {
return fmt.Sprintf("%.2d:%.2d", t.Hour(), t.Minute())
}

// has checks if a string slice has the given element
func has(sl []string, e string) bool {
for _, s := range sl {
Expand Down Expand Up @@ -81,3 +87,65 @@ func containsE(envVar, subString string) bool {
func hasE(envVar string) bool {
return os.Getenv(envVar) != ""
}

// CommonPrefix will find the longest common prefix in a slice of strings
func CommonPrefix(sl []string) string {
if len(sl) == 0 {
return ""
}
shortestLength := len(sl[0])
shortestString := sl[0]
for _, s := range sl {
if len(s) < shortestLength {
shortestLength = len(s)
shortestString = s
}
}
if shortestLength == 0 {
return ""
}
for i := 1; i < shortestLength; i++ {
for _, s := range sl {
if !strings.HasPrefix(s, shortestString[:i]) {
return shortestString[:i-1]
}
}
}
return shortestString
}

// CommonPrefix will find the longest common suffix in a slice of strings
func CommonSuffix(sl []string) string {
if len(sl) == 0 {
return ""
}
shortestLength := len(sl[0])
shortestString := sl[0]
for _, s := range sl {
if len(s) < shortestLength {
shortestLength = len(s)
shortestString = s
}
}
if shortestLength == 0 {
return ""
}
for i := 1; i < shortestLength; i++ {
for _, s := range sl {
if !strings.HasSuffix(s, shortestString[shortestLength-i:]) {
return shortestString[shortestLength-(i-1):]
}
}
}
return shortestString
}

// Meat returns the meat of the string: the part that is after the prefix and
// before the suffix. Will return the given string if it is too short to
// contain the prefix and suffix.
func Meat(s, prefix, suffix string) string {
if len(s) < (len(prefix) + len(suffix)) {
return s
}
return s[len(prefix) : len(s)-len(suffix)]
}

0 comments on commit 775bba9

Please sign in to comment.