helper/schema: track map of swaps

This commit is contained in:
Mitchell Hashimoto 2014-08-20 16:34:50 -07:00
parent 5e975e47cf
commit 312acf3e40
2 changed files with 29 additions and 2 deletions

View File

@ -4,6 +4,7 @@ package schema
// to a schema. // to a schema.
type listSort struct { type listSort struct {
List []interface{} List []interface{}
Map map[int]int
Schema *Schema Schema *Schema
} }
@ -17,4 +18,19 @@ func (s *listSort) Less(i, j int) bool {
func (s *listSort) Swap(i, j int) { func (s *listSort) Swap(i, j int) {
s.List[i], s.List[j] = s.List[j], s.List[i] s.List[i], s.List[j] = s.List[j], s.List[i]
// Build the mapping. We have to make sure we get to the proper
// place where the final target is, not the current value.
if s.Map == nil {
s.Map = make(map[int]int)
}
i2 := i
j2 := j
if v, ok := s.Map[i]; ok {
i2 = v
}
if v, ok := s.Map[j]; ok {
j2 = v
}
s.Map[i], s.Map[j] = j2, i2
} }

View File

@ -12,7 +12,7 @@ func TestListSort_impl(t *testing.T) {
func TestListSort(t *testing.T) { func TestListSort(t *testing.T) {
s := &listSort{ s := &listSort{
List: []interface{}{5, 2, 1}, List: []interface{}{5, 2, 1, 3, 4},
Schema: &Schema{ Schema: &Schema{
Order: func(a, b interface{}) bool { Order: func(a, b interface{}) bool {
return a.(int) < b.(int) return a.(int) < b.(int)
@ -22,8 +22,19 @@ func TestListSort(t *testing.T) {
sort.Sort(s) sort.Sort(s)
expected := []interface{}{1, 2, 5} expected := []interface{}{1, 2, 3, 4, 5}
if !reflect.DeepEqual(s.List, expected) { if !reflect.DeepEqual(s.List, expected) {
t.Fatalf("bad: %#v", s.List) t.Fatalf("bad: %#v", s.List)
} }
expectedMap := map[int]int{
0: 2,
1: 1,
2: 3,
3: 4,
4: 0,
}
if !reflect.DeepEqual(s.Map, expectedMap) {
t.Fatalf("bad: %#v", s.Map)
}
} }