2018-10-06 03:27:34 +02:00
|
|
|
package arrays
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2018-10-14 19:06:27 +02:00
|
|
|
|
2018-10-06 03:27:34 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
2019-02-13 19:31:18 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values/types"
|
2018-10-06 03:27:34 +02:00
|
|
|
)
|
|
|
|
|
2018-10-14 19:06:27 +02:00
|
|
|
// RemoveValue returns a new array with removed all occurrences of value in a given array.
|
|
|
|
// Optionally with a limit to the number of removals.
|
|
|
|
// @param array (Array) - Source array.
|
|
|
|
// @param value (Read) - Target value.
|
|
|
|
// @param limit (Int, optional) - A limit to the number of removals.
|
|
|
|
// @returns (Array) - A new array with removed all occurrences of value in a given array.
|
2018-10-06 03:27:34 +02:00
|
|
|
func RemoveValue(_ context.Context, args ...core.Value) (core.Value, error) {
|
|
|
|
err := core.ValidateArgs(args, 2, 3)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(args[0], types.Array)
|
2018-10-06 03:27:34 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
arr := args[0].(*values.Array)
|
|
|
|
value := args[1]
|
|
|
|
limit := -1
|
|
|
|
|
|
|
|
if len(args) > 2 {
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(args[2], types.Int)
|
2018-10-06 03:27:34 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
limit = int(args[2].(values.Int))
|
|
|
|
}
|
|
|
|
|
|
|
|
result := values.NewArray(int(arr.Length()))
|
|
|
|
|
|
|
|
counter := 0
|
|
|
|
arr.ForEach(func(item core.Value, idx int) bool {
|
|
|
|
remove := item.Compare(value) == 0
|
|
|
|
|
|
|
|
if remove {
|
|
|
|
if counter == limit {
|
|
|
|
result.Push(item)
|
|
|
|
}
|
|
|
|
|
|
|
|
counter++
|
|
|
|
} else {
|
|
|
|
result.Push(item)
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|