From 109a45e9a0bc2370aa3bc106c3267b713a5c1688 Mon Sep 17 00:00:00 2001 From: Marius Orcsik Date: Sun, 20 Mar 2022 15:15:07 +0100 Subject: [PATCH] Added a ItemCollection.Normalize method It allows us to return an the first element in a collection if there is just one --- flatten.go | 2 +- item_collection.go | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/flatten.go b/flatten.go index c644a8c..66c5828 100644 --- a/flatten.go +++ b/flatten.go @@ -118,7 +118,7 @@ func Flatten(it Item) Item { } if it.IsCollection() { if c, ok := it.(CollectionInterface); ok { - it = FlattenItemCollection(c.Collection()) + it = FlattenItemCollection(c.Collection()).Normalize() } } if len(it.GetLink()) > 0 { diff --git a/item_collection.go b/item_collection.go index edc2c9c..0a1fd29 100644 --- a/item_collection.go +++ b/item_collection.go @@ -64,6 +64,19 @@ func (i ItemCollection) First() Item { return i[0] } +// Normalize returns the first item if the collection contains only one, +// the full collection if the collection contains more than one item, +// or nil +func (i ItemCollection) Normalize() Item { + if len(i) == 0 { + return nil + } + if len(i) == 1 { + return i[0] + } + return i +} + // Collection returns the current object as collection interface func (i *ItemCollection) Collection() ItemCollection { return *i