Skip to content

Instantly share code, notes, and snippets.

@odeke-em
Last active August 29, 2015 14:15
Show Gist options
  • Save odeke-em/ee2fd6d12bc65ccae7b4 to your computer and use it in GitHub Desktop.
Save odeke-em/ee2fd6d12bc65ccae7b4 to your computer and use it in GitHub Desktop.
commonPrefix.go
package main
import "fmt"
func commonPrefix(values ...string) string {
vLen := len(values)
if vLen < 1 {
return ""
}
minIndex := 0
min := values[0]
minLen := len(min)
for i := 1; i < vLen; i += 1 {
st := values[i]
if st == "" {
return ""
}
lst := len(st)
if lst < minLen {
min = st
minLen = lst
minIndex = i + 0
}
}
prefix := make([]byte, minLen)
matchOn := true
for i := 0; i < minLen; i += 1 {
for j, other := range values {
if minIndex == j {
continue
}
if other[i] != min[i] {
matchOn = false
break
}
}
if !matchOn {
break
}
prefix[i] = min[i]
}
return string(prefix)
}
func main() {
prefix := commonPrefix("/mnt/openSrc", "/mnt//", "/mnt/custom", "/mnt/openSrc/io.js")
fmt.Println(prefix) // Should return "/mnt/"
prefix = commonPrefix("/usr/lib/openSrc", "/mnt//", "/mnt/openSrc/io.js")
fmt.Println(prefix) // Should return "/"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment