2018-10-05 21:27:34 -04:00
|
|
|
package arrays
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2018-10-14 20:06:27 +03:00
|
|
|
|
2018-10-05 21:27:34 -04:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/collections"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
|
|
)
|
|
|
|
|
2018-10-14 20:06:27 +03:00
|
|
|
// SortedUnique sorts all elements in anyArray.
|
|
|
|
// The function will use the default comparison order for FQL value types.
|
|
|
|
// Additionally, the values in the result array will be made unique
|
|
|
|
// @param array (Array) - Target array.
|
|
|
|
// @returns (Array) - Sorted array.
|
2018-10-05 21:27:34 -04:00
|
|
|
func SortedUnique(_ context.Context, args ...core.Value) (core.Value, error) {
|
|
|
|
err := core.ValidateArgs(args, 1, 1)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = core.ValidateType(args[0], core.ArrayType)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
arr := args[0].(*values.Array)
|
|
|
|
|
|
|
|
if arr.Length() == 0 {
|
|
|
|
return values.NewArray(0), nil
|
|
|
|
}
|
|
|
|
|
2018-10-24 21:30:05 -04:00
|
|
|
sorter, err := collections.NewSorter(func(first collections.DataSet, second collections.DataSet) (int, error) {
|
|
|
|
return first.Get(collections.DefaultValueVar).Compare(second.Get(collections.DefaultValueVar)), nil
|
2018-10-05 21:27:34 -04:00
|
|
|
}, collections.SortDirectionAsc)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
2018-10-24 21:30:05 -04:00
|
|
|
uniqIterator, err := collections.NewUniqueIterator(
|
|
|
|
collections.NewDefaultIndexedIterator(arr),
|
|
|
|
collections.DefaultValueVar,
|
|
|
|
)
|
2018-10-05 21:27:34 -04:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
iterator, err := collections.NewSortIterator(
|
|
|
|
uniqIterator,
|
|
|
|
sorter,
|
|
|
|
)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
2018-10-24 21:30:05 -04:00
|
|
|
return toArray(iterator)
|
2018-10-05 21:27:34 -04:00
|
|
|
}
|