package logic import ( "strings" "git.milar.in/milarin/gmath" "git.milar.in/milarin/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 }) }