diff --git a/docs/docs/literals/array.md b/docs/docs/literals/array.md index 950d37c..761a4e0 100644 --- a/docs/docs/literals/array.md +++ b/docs/docs/literals/array.md @@ -126,6 +126,15 @@ Sorts the array if it contains only one type of STRING, INTEGER or FLOAT ' /> +### sum() +> Returns `INTEGER` + + + + + + + ### uniq() > Returns `ARRAY|ERROR` diff --git a/object/array.go b/object/array.go index 7ff6a61..c432a58 100644 --- a/object/array.go +++ b/object/array.go @@ -196,6 +196,26 @@ func init() { return ao }, }, + "sum": ObjectMethod{ + Layout: MethodLayout{ + ReturnPattern: Args( + Arg(INTEGER_OBJ), + ), + }, + method: func(o Object, _ []Object, _ Environment) Object { + ao := o.(*Array) + var result int + + for i, element := range ao.Elements { + if val, ok := element.(Integerable); ok { + result += int(val.ToIntegerObj(nil).Value) + } else { + return NewErrorFormat("Found non number element %s on index %d", element.Type(), i) + } + } + return NewInteger(int64(result)) + }, + }, "uniq": ObjectMethod{ Layout: MethodLayout{ ReturnPattern: Args( diff --git a/object/array_test.go b/object/array_test.go index 41502d7..b47b549 100644 --- a/object/array_test.go +++ b/object/array_test.go @@ -72,6 +72,8 @@ func TestArrayObjectMethods(t *testing.T) { {"[1,2,3,{}].join()", "Found non stringable element HASH on index 3"}, {"[1,2,3].join()", "123"}, {"[1,2,3].join('-')", "1-2-3"}, + {"['1',2, 2.5,{}].sum()", "Found non number element HASH on index 3"}, + {"['1', 2, 2.5].sum()", 5}, } testInput(t, tests)