67 lines
1.0 KiB
Go
67 lines
1.0 KiB
Go
package compare
|
|
|
|
import (
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
const maxItems = 2
|
|
|
|
func Parse(raw string) []int {
|
|
if raw == "" {
|
|
return nil
|
|
}
|
|
var ids []int
|
|
for _, part := range strings.Split(raw, ",") {
|
|
id, err := strconv.Atoi(strings.TrimSpace(part))
|
|
if err != nil || id <= 0 {
|
|
continue
|
|
}
|
|
ids = appendUnique(ids, id)
|
|
}
|
|
return ids
|
|
}
|
|
|
|
func Format(ids []int) string {
|
|
if len(ids) == 0 {
|
|
return ""
|
|
}
|
|
parts := make([]string, len(ids))
|
|
for i, id := range ids {
|
|
parts[i] = strconv.Itoa(id)
|
|
}
|
|
return strings.Join(parts, ",")
|
|
}
|
|
|
|
func Add(raw string, id int) string {
|
|
if id <= 0 {
|
|
return raw
|
|
}
|
|
ids := Parse(raw)
|
|
ids = appendUnique(ids, id)
|
|
if len(ids) > maxItems {
|
|
ids = ids[len(ids)-maxItems:]
|
|
}
|
|
return Format(ids)
|
|
}
|
|
|
|
func Remove(raw string, id int) string {
|
|
ids := Parse(raw)
|
|
var next []int
|
|
for _, v := range ids {
|
|
if v != id {
|
|
next = append(next, v)
|
|
}
|
|
}
|
|
return Format(next)
|
|
}
|
|
|
|
func appendUnique(ids []int, id int) []int {
|
|
for _, v := range ids {
|
|
if v == id {
|
|
return ids
|
|
}
|
|
}
|
|
return append(ids, id)
|
|
}
|