Added a ItemCollection.Normalize method

It allows us to return an the first element in a collection if there is just one
This commit is contained in:
Marius Orcsik 2022-03-20 15:15:07 +01:00
parent 0b791c7c7f
commit 109a45e9a0
No known key found for this signature in database
GPG key ID: DBF5E47F5DBC4D21
2 changed files with 14 additions and 1 deletions

View file

@ -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 {

View file

@ -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