Skip to content

Commit

Permalink
Sort required fields before others (#78)
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Bandy <bandy.chris@gmail.com>
  • Loading branch information
cbandy authored Sep 11, 2021
1 parent 47f3978 commit fa9ffd4
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pkg/builder/properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ func (s propertiesByRequired) Less(i, j int) bool {
}

if leftRequired && !rightRequired {
return false
return true
}
if !leftRequired && rightRequired {
return true
return false
}
return left < right
}
Expand Down
48 changes: 48 additions & 0 deletions pkg/builder/properties_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright 2021 IBM Corp.
// SPDX-License-Identifier: Apache-2.0

package builder

import (
"math/rand"
"reflect"
"sort"
"testing"
)

func TestSortPropertiesByRequired(t *testing.T) {
shuffle := func(s []string) {
rand.Shuffle(len(s), func(i, j int) {
s[i], s[j] = s[j], s[i]
})
}

sorter := propertiesByRequired{}

// No required; sorts alphabetically.
sorter.properties = []string{"a", "b", "c", "d"}
shuffle(sorter.properties)
sort.Sort(sorter)

if !reflect.DeepEqual(sorter.properties, []string{"a", "b", "c", "d"}) {
t.Fatalf("wrong order, got %v", sorter.properties)
}

// Required first.
sorter.required = []string{"b", "d"}
shuffle(sorter.properties)
sort.Sort(sorter)

if !reflect.DeepEqual(sorter.properties, []string{"b", "d", "a", "c"}) {
t.Fatalf("wrong order, got %v", sorter.properties)
}

// All required; sorts alphabetically.
sorter.required = []string{"a", "b", "c", "d"}
shuffle(sorter.properties)
sort.Sort(sorter)

if !reflect.DeepEqual(sorter.properties, []string{"a", "b", "c", "d"}) {
t.Fatalf("wrong order, got %v", sorter.properties)
}
}

0 comments on commit fa9ffd4

Please sign in to comment.