v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/util/maps/flat.go (about) 1 package maps 2 3 import "sort" 4 5 type KeyValue[K comparable, V any] struct { 6 Key K 7 Value V 8 } 9 10 func FlatMap[K comparable, V any](m map[K]V) []KeyValue[K, V] { 11 if m == nil { 12 return nil 13 } 14 var kvs []KeyValue[K, V] = make([]KeyValue[K, V], len(m)) 15 if len(kvs) == 0 { 16 return kvs 17 } 18 19 var i int = len(kvs) - 1 20 for k, v := range m { 21 kvs[i] = KeyValue[K, V]{k, v} 22 i-- 23 } 24 25 var key K 26 27 // Sort the array by key. 28 switch any(&key).(type) { 29 case *uint: 30 sort.Slice(kvs, func(i, j int) bool { 31 return *any(&kvs[i].Key).(*uint) < *any(&kvs[j].Key).(*uint) 32 }) 33 case *int: 34 sort.Slice(kvs, func(i, j int) bool { 35 return *any(&kvs[i].Key).(*int) < *any(&kvs[j].Key).(*int) 36 }) 37 case *uint8: 38 sort.Slice(kvs, func(i, j int) bool { 39 return *any(&kvs[i].Key).(*uint8) < *any(&kvs[j].Key).(*uint8) 40 }) 41 case *uint16: 42 sort.Slice(kvs, func(i, j int) bool { 43 return *any(&kvs[i].Key).(*uint16) < *any(&kvs[j].Key).(*uint16) 44 }) 45 case *uint32: 46 sort.Slice(kvs, func(i, j int) bool { 47 return *any(&kvs[i].Key).(*uint32) < *any(&kvs[j].Key).(*uint32) 48 }) 49 case *uint64: 50 sort.Slice(kvs, func(i, j int) bool { 51 return *any(&kvs[i].Key).(*uint64) < *any(&kvs[j].Key).(*uint64) 52 }) 53 case *int8: 54 sort.Slice(kvs, func(i, j int) bool { 55 return *any(&kvs[i].Key).(*int8) < *any(&kvs[j].Key).(*int8) 56 }) 57 case *int16: 58 sort.Slice(kvs, func(i, j int) bool { 59 return *any(&kvs[i].Key).(*int16) < *any(&kvs[j].Key).(*int16) 60 }) 61 case *int32: 62 sort.Slice(kvs, func(i, j int) bool { 63 return *any(&kvs[i].Key).(*int32) < *any(&kvs[j].Key).(*int32) 64 }) 65 case *int64: 66 sort.Slice(kvs, func(i, j int) bool { 67 return *any(&kvs[i].Key).(*int64) < *any(&kvs[j].Key).(*int64) 68 }) 69 case *float32: 70 sort.Slice(kvs, func(i, j int) bool { 71 return *any(&kvs[i].Key).(*float32) < *any(&kvs[j].Key).(*float32) 72 }) 73 case *float64: 74 sort.Slice(kvs, func(i, j int) bool { 75 return *any(&kvs[i].Key).(*float64) < *any(&kvs[j].Key).(*float64) 76 }) 77 case *string: 78 sort.Slice(kvs, func(i, j int) bool { 79 return *any(&kvs[i].Key).(*string) < *any(&kvs[j].Key).(*string) 80 }) 81 case *uintptr: 82 sort.Slice(kvs, func(i, j int) bool { 83 return *any(&kvs[i].Key).(*uintptr) < *any(&kvs[j].Key).(*uintptr) 84 }) 85 } 86 87 return kvs 88 }