From a64046e5c1e0eda5f334a76b7c11652cc4726de9 Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Thu, 12 May 2016 20:07:22 -0400 Subject: [PATCH] Added method VersionCompare which can be used for custom version sorting --- changelog.md | 4 ++++ sortutil/sortutil.go | 36 +++++++++++++++++++++--------------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/changelog.md b/changelog.md index b09ff57e..c854bea5 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,9 @@ ## Changelog +#### v1.8.1 + +* `[sortutil]` Added method `VersionCompare` which can be used for custom version sorting + #### v1.8.0 * `[sortutil]` Added case insensitive strings sorting diff --git a/sortutil/sortutil.go b/sortutil/sortutil.go index a6c5c578..132d49a0 100644 --- a/sortutil/sortutil.go +++ b/sortutil/sortutil.go @@ -24,8 +24,27 @@ type stringSlice []string func (s versionSlice) Len() int { return len(s) } func (s versionSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s versionSlice) Less(i, j int) bool { - is := strings.Split(s[i], ".") - js := strings.Split(s[j], ".") + return VersionCompare(s[i], s[j]) +} + +func (s stringSlice) Len() int { return len(s) } +func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s stringSlice) Less(i, j int) bool { + return strings.ToLower(s[i]) < strings.ToLower(s[j]) +} + +// ////////////////////////////////////////////////////////////////////////////////// // + +// Versions sort versions slice +func Versions(s []string) { + sort.Sort(versionSlice(s)) +} + +// VersionsCompare compare 2 versions and return true if v1 less v2. This function +// can ve used for version sorting with structs +func VersionCompare(v1, v2 string) bool { + is := strings.Split(v1, ".") + js := strings.Split(v2, ".") il, jl := len(is), len(js) @@ -65,19 +84,6 @@ func (s versionSlice) Less(i, j int) bool { return true } -func (s stringSlice) Len() int { return len(s) } -func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s stringSlice) Less(i, j int) bool { - return strings.ToLower(s[i]) < strings.ToLower(s[j]) -} - -// ////////////////////////////////////////////////////////////////////////////////// // - -// Versions sort versions slice -func Versions(s []string) { - sort.Sort(versionSlice(s)) -} - // Strings sort strings slice and support case insensitive mode func Strings(s []string, caseInsensitive bool) { if caseInsensitive {