map.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package slices
  2. import "reflect"
  3. type MapItem struct {
  4. Key, Elem interface{}
  5. }
  6. // Creates a []struct{Key K; Value V} for map[K]V.
  7. func FromMap(m interface{}) (slice []MapItem) {
  8. mapValue := reflect.ValueOf(m)
  9. for _, key := range mapValue.MapKeys() {
  10. slice = append(slice, MapItem{key.Interface(), mapValue.MapIndex(key).Interface()})
  11. }
  12. return
  13. }
  14. // Returns all the elements []T, from m where m is map[K]T.
  15. func FromMapElems(m interface{}) interface{} {
  16. inValue := reflect.ValueOf(m)
  17. outValue := reflect.MakeSlice(reflect.SliceOf(inValue.Type().Elem()), inValue.Len(), inValue.Len())
  18. for i, key := range inValue.MapKeys() {
  19. outValue.Index(i).Set(inValue.MapIndex(key))
  20. }
  21. return outValue.Interface()
  22. }
  23. // Returns all the elements []K, from m where m is map[K]T.
  24. func FromMapKeys(m interface{}) interface{} {
  25. inValue := reflect.ValueOf(m)
  26. outValue := reflect.MakeSlice(reflect.SliceOf(inValue.Type().Key()), inValue.Len(), inValue.Len())
  27. for i, key := range inValue.MapKeys() {
  28. outValue.Index(i).Set(key)
  29. }
  30. return outValue.Interface()
  31. }
  32. // f: (T)T, input: []T, outout: []T
  33. func Map(f, input interface{}) interface{} {
  34. inputValue := reflect.ValueOf(input)
  35. funcValue := reflect.ValueOf(f)
  36. _len := inputValue.Len()
  37. retValue := reflect.MakeSlice(reflect.TypeOf(input), _len, _len)
  38. for i := 0; i < _len; i++ {
  39. out := funcValue.Call([]reflect.Value{inputValue.Index(i)})
  40. retValue.Index(i).Set(out[0])
  41. }
  42. return retValue.Interface()
  43. }