github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/unshift.go (about) 1 package arrays 2 3 import ( 4 "context" 5 6 "github.com/MontFerret/ferret/pkg/runtime/core" 7 "github.com/MontFerret/ferret/pkg/runtime/values" 8 "github.com/MontFerret/ferret/pkg/runtime/values/types" 9 ) 10 11 // UNSHIFT prepends value to a given array. 12 // @param {Any[]} array - Target array. 13 // @param {Any} value - Target value to prepend. 14 // @param {Boolean} [unique=False] - Optional value indicating whether a value must be unique to be prepended. Default is false. 15 // @return {Any[]} - New array with prepended value. 16 func Unshift(_ context.Context, args ...core.Value) (core.Value, error) { 17 err := core.ValidateArgs(args, 2, 3) 18 19 if err != nil { 20 return values.None, err 21 } 22 23 err = core.ValidateType(args[0], types.Array) 24 25 if err != nil { 26 return values.None, err 27 } 28 29 arr := args[0].(*values.Array) 30 value := args[1] 31 uniq := values.False 32 33 if len(args) > 2 { 34 err = core.ValidateType(args[2], types.Boolean) 35 36 if err != nil { 37 return values.None, err 38 } 39 40 uniq = args[2].(values.Boolean) 41 } 42 43 result := values.NewArray(int(arr.Length() + 1)) 44 45 if !uniq { 46 result.Push(value) 47 48 arr.ForEach(func(el core.Value, _ int) bool { 49 result.Push(el) 50 51 return true 52 }) 53 } else { 54 ok := true 55 56 // let's just hope it's unique 57 // if not, we will terminate the loop and return a copy of an array 58 result.Push(value) 59 60 arr.ForEach(func(el core.Value, idx int) bool { 61 if el.Compare(value) != 0 { 62 result.Push(el) 63 64 return true 65 } 66 67 // not unique 68 ok = false 69 return false 70 }) 71 72 if !ok { 73 // value is not unique, just return a new copy with same elements 74 return arr.Copy(), nil 75 } 76 } 77 78 return result, nil 79 }