1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/stdlib/objects/merge.go
3timeslazy 446ce3ead5 added MERGE object function (#111)
* add pkg/stdlib/objects Length function

* rename lenght.go -> length.go

* fix tests according to other tests

* add new tests to length tests

* delete objects method Length

* add objects method Has

* add objects function Keys

* small fixes in Keys and Has functions

* change Has function

* unit tests for Keys function

* add unit tests for merge. also little change in lib.go

* add doc to Keys function

* Merge function prototype

* add unit tests for KEEP function

* added KEEP function

* added doc for KEYS function

* update lib.go

* update lib.go

* upd merge prototype

* addded isEqualObjects function to objects tests

* change object method Compare

* added unit tests for Compare method

* changed Compare method

* fix Compare method

* rename method Clone to Copy

* added Cloneable interface

* added Value to Cloneable interface

* implemented Cloneable intefrace by array

* added some more unit tests for values.Array

* fix values.Array.Compare method

* added one more unit test

* implemented Cloneable interface by Object

* unit tests for Object.Clone

* move core.IsCloneable to value.go

* change Clone function

* move IsClonable to package values

* updated MERGE unit tests

* added MERGE function

* added MERGE to lib

* added one more test

* changed MERGE function
2018-10-13 13:04:00 -04:00

64 lines
1.4 KiB
Go

package objects
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
/*
* Merge the given objects into a single object.
* @params objs (Array Of Object OR Objects) - objects to merge.
* @returns (Object) - Object created by merging.
*/
func Merge(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 1, core.MaxArgs)
if err != nil {
return values.None, err
}
objs := values.NewArrayWith(args...)
if len(args) == 1 && args[0].Type() == core.ArrayType {
objs = args[0].(*values.Array)
}
err = validateArrayOf(core.ObjectType, objs)
if err != nil {
return values.None, err
}
return mergeArray(objs), nil
}
func mergeArray(arr *values.Array) *values.Object {
merged, obj := values.NewObject(), values.NewObject()
arr.ForEach(func(arrValue core.Value, arrIdx int) bool {
obj = arrValue.(*values.Object)
obj.ForEach(func(objValue core.Value, objKey string) bool {
if values.IsCloneable(objValue) {
objValue = objValue.(core.Cloneable).Clone()
}
merged.Set(values.NewString(objKey), objValue)
return true
})
return true
})
return merged
}
func validateArrayOf(typ core.Type, arr *values.Array) (err error) {
for idx := values.NewInt(0); idx < arr.Length(); idx++ {
if err != nil {
break
}
err = core.ValidateType(arr.Get(idx), typ)
}
return
}