From b886a5576a986a2fe70a47dbf722769ddbfe9500 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Sun, 13 May 2018 22:15:54 +0100 Subject: [PATCH] Return empty array if requested array range If an array range was requested, but no values matched, then a nil value was returned, instead of an empty array. Now an empty array is returned if regardless of whether there are any matching array values or not. --- util/data/data.go | 14 ++++++++++++-- util/data/data_test.go | 8 ++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/util/data/data.go b/util/data/data.go index 8ade17a3..81a5fe7a 100644 --- a/util/data/data.go +++ b/util/data/data.go @@ -505,7 +505,12 @@ func (d *Doc) Fetch(call Fetcher, path ...string) *Doc { c, _, r := d.what(p, a, choose) if len(c) == 0 { - return &Doc{data: nil} + switch r { + case one: + return &Doc{data: nil} + case many: + return &Doc{data: []interface{}{}} + } } if r == one { @@ -594,7 +599,12 @@ func (d *Doc) Set(value interface{}, path ...string) (*Doc, error) { c, i, r := d.what(p, a, choose) if len(c) == 0 { - return &Doc{data: nil}, nil + switch r { + case one: + return &Doc{data: nil}, nil + case many: + return &Doc{data: []interface{}{}}, nil + } } if r == one { diff --git a/util/data/data_test.go b/util/data/data_test.go index d69f12a4..34ab41bc 100644 --- a/util/data/data_test.go +++ b/util/data/data_test.go @@ -633,10 +633,10 @@ func TestOperations(t *testing.T) { So(doc.Get("the.item.tags[2:4]").Data(), ShouldResemble, []interface{}{"Sticky", "Warm"}) So(doc.Get("the.item.tags[2:5]").Data(), ShouldResemble, []interface{}{"Sticky", "Warm"}) So(doc.Get("the.item.tags[2:9]").Data(), ShouldResemble, []interface{}{"Sticky", "Warm"}) - So(doc.Get("the.item.tags[4:5]").Data(), ShouldResemble, nil) - So(doc.Get("the.item.tags[8:9]").Data(), ShouldResemble, nil) - So(doc.Get("the.item.tags[0:none]").Data(), ShouldResemble, nil) - So(doc.Get("the.item.tags[0:none:some]").Data(), ShouldResemble, nil) + So(doc.Get("the.item.tags[4:5]").Data(), ShouldResemble, []interface{}{}) + So(doc.Get("the.item.tags[8:9]").Data(), ShouldResemble, []interface{}{}) + So(doc.Get("the.item.tags[0:none]").Data(), ShouldResemble, []interface{}{}) + So(doc.Get("the.item.tags[0:none:some]").Data(), ShouldResemble, []interface{}{}) }) Convey("Can add single to array", t, func() {