Skip to content

Commit

Permalink
Merge pull request #178 from Flipez/array-sum
Browse files Browse the repository at this point in the history
[object/array] Add ability to `.sum()` elements
  • Loading branch information
Flipez authored Dec 19, 2022
2 parents 143c0c3 + 13e9728 commit c3c2bc2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/docs/literals/array.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
20 changes: 20 additions & 0 deletions object/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions object/array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

2 comments on commit c3c2bc2

@vercel
Copy link

@vercel vercel bot commented on c3c2bc2 Dec 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on c3c2bc2 Dec 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.