Skip to content

Commit

Permalink
feat: add IterateInOrder function
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Oct 26, 2020
1 parent fc697f0 commit 06d564d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
28 changes: 28 additions & 0 deletions document/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,34 @@ func Fields(d Document) ([]string, error) {
return fields, nil
}

func IterateInOrder(d Document, fn func(string, Value) error) error {
type pair struct {
field string
value Value
}
var pairs []pair

err := d.Iterate(func(field string, value Value) error {
pairs = append(pairs, pair{field, value})
return nil
})
if err != nil {
return err
}

sort.Slice(pairs, func(i, j int) bool {
return strings.Compare(pairs[i].field, pairs[j].field) == -1
})

for _, p := range pairs {
err := fn(p.field, p.value)
if err != nil {
return err
}
}
return nil
}

// FieldBuffer stores a group of fields in memory. It implements the Document interface.
type FieldBuffer struct {
fields []fieldValue
Expand Down
16 changes: 16 additions & 0 deletions document/document_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -665,3 +665,19 @@ func BenchmarkDocumentIterate(b *testing.B) {
}
})
}

func TestIterateInOrder(t *testing.T) {
fb := new(document.FieldBuffer)

fb.Add("zyx", document.NewIntegerValue(3))
fb.Add("abc", document.NewIntegerValue(1))
fb.Add("cba", document.NewIntegerValue(2))

i := int64(0)
err := document.IterateInOrder(fb, func(_ string, value document.Value) error {
i++
require.Equal(t, i, value.V.(int64))
return nil
})
require.NoError(t, err)
}

0 comments on commit 06d564d

Please sign in to comment.