50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
|
package input
|
||
|
|
||
|
import "strconv"
|
||
|
|
||
|
// ListBinder describes the interface that anything that wants to present key value pairs needs to implement.
|
||
|
type ListBinder interface {
|
||
|
ListKeyValuePairs() []ListKeyValuePair
|
||
|
}
|
||
|
|
||
|
type ListKeyValuePair struct {
|
||
|
Key, Value string
|
||
|
}
|
||
|
|
||
|
// ListBindGenericSlice implements ListBinder for slices that are of some arbitrary type.
|
||
|
// For this to work, you need to supply a function that returns key value pairs for every slice entry.
|
||
|
type ListBindGenericSlice[T any] struct {
|
||
|
Slice *[]T
|
||
|
KeyValueFunc func(index int, entry T) ListKeyValuePair
|
||
|
}
|
||
|
|
||
|
func (l ListBindGenericSlice[T]) ListKeyValuePairs() []ListKeyValuePair {
|
||
|
if l.Slice == nil || l.KeyValueFunc == nil {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
result := make([]ListKeyValuePair, 0, len(*l.Slice))
|
||
|
for i, entry := range *l.Slice {
|
||
|
result = append(result, l.KeyValueFunc(i, entry))
|
||
|
}
|
||
|
return result
|
||
|
}
|
||
|
|
||
|
// ListBindSlice implements ListBinder for string slices.
|
||
|
// The list index (as a string) is used as a key.
|
||
|
type ListBindSlice struct {
|
||
|
Slice *[]string
|
||
|
}
|
||
|
|
||
|
func (l ListBindSlice) ListKeyValuePairs() []ListKeyValuePair {
|
||
|
if l.Slice == nil {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
result := make([]ListKeyValuePair, 0, len(*l.Slice))
|
||
|
for i, entry := range *l.Slice {
|
||
|
result = append(result, ListKeyValuePair{Key: strconv.Itoa(i), Value: entry})
|
||
|
}
|
||
|
return result
|
||
|
}
|