Skip to content

Commit

Permalink
Add support for ARRAY.sort()
Browse files Browse the repository at this point in the history
Signed-off-by: Flipez <code@brauser.io>
  • Loading branch information
Flipez committed Oct 30, 2022
1 parent 9091d92 commit 29eb569
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
12 changes: 12 additions & 0 deletions docs/docs/literals/array.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ Returns the last element of the array.
```


### reverse()
> Returns `ARRAY`
Reverses the elements of the array


```js
🚀 > ["a", "b", 1, 2].reverse()
=> [2, 1, "b", "a"]
```


### size()
> Returns `INTEGER`
Expand Down
18 changes: 18 additions & 0 deletions object/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ func (ao *Array) Add(items ...any) {

func init() {
objectMethods[ARRAY_OBJ] = map[string]ObjectMethod{
"reverse": ObjectMethod{
Layout: MethodLayout{
Description: "Reverses the elements of the array",
Example: `🚀 > ["a", "b", 1, 2].reverse()
=> [2, 1, "b", "a"]`,
ReturnPattern: Args(
Arg(ARRAY_OBJ),
),
},
method: func(o Object, _ []Object, _ Environment) Object {
ao := o.(*Array)

for i, j := 0, len(ao.Elements)-1; i < j; i, j = i+1, j-1 {
ao.Elements[i], ao.Elements[j] = ao.Elements[j], ao.Elements[i]
}
return ao
},
},
"size": ObjectMethod{
Layout: MethodLayout{
Description: "Returns the amount of elements in the array.",
Expand Down
1 change: 1 addition & 0 deletions object/array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func TestArrayObjectMethods(t *testing.T) {
{`[2.0, "Go", 2.0].sort()`, "Array does contain either an object not INTEGER, FLOAT or STRING or is mixed"},
{`[true, "Go", true].sort()`, "Array does contain either an object not INTEGER, FLOAT or STRING or is mixed"},
{`[].sort()`, `[]`},
{`["a", "b", 1, 2].reverse()`, `[2, 1, "b", "a"]`},
}

testInput(t, tests)
Expand Down

0 comments on commit 29eb569

Please sign in to comment.