initial commit
This commit is contained in:
53
preferred_props.go
Normal file
53
preferred_props.go
Normal file
@ -0,0 +1,53 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.tordarus.net/tordarus/gmath"
|
||||
"git.tordarus.net/tordarus/slices"
|
||||
)
|
||||
|
||||
// ParsePreferredProps parses properties and its corresponding priority.
|
||||
// priorities are distributed exponentially in reverse order.
|
||||
//
|
||||
// That means the last entry will have priority 1, the second last 2, then 4, 8 and so on.
|
||||
//
|
||||
// Properties with name "_" will be ignored and function as a placeholder to increase the priority
|
||||
// of the properties which comes before them.
|
||||
//
|
||||
// Properties separated by comma will have the same priorities.
|
||||
//
|
||||
// str usually is the return value of a call to strings.Split(str, "|")
|
||||
//
|
||||
// Examples:
|
||||
// str = "a|b|c" -> c:1 b:2 a:4
|
||||
// str = "a|b|_|c" -> c:1 b:4 a:8
|
||||
// str = "a,b|c" -> c:1 b:4 a:4
|
||||
// str = "d|_|a,b|c" -> c:1 b:4 a:4 d:16
|
||||
//
|
||||
// Additionally, properties can be converted to a generic type with the converter function
|
||||
func ParsePreferredProps[T comparable](str []string, converter func(string) (T, error)) map[T]int {
|
||||
props := map[T]int{}
|
||||
|
||||
for i, subProps := range slices.Reverse(str) {
|
||||
if subProps == "_" {
|
||||
continue
|
||||
}
|
||||
|
||||
propPriority := gmath.Pow(2, i)
|
||||
for _, subProp := range strings.Split(subProps, ",") {
|
||||
subPropT, err := converter(subProp)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
props[subPropT] = propPriority
|
||||
}
|
||||
}
|
||||
|
||||
return props
|
||||
}
|
||||
|
||||
func ParsePreferredStringProps(str []string) map[string]int {
|
||||
return ParsePreferredProps(str, func(s string) (string, error) { return s, nil })
|
||||
}
|
Reference in New Issue
Block a user