Skip to content

Commit

Permalink
object/array: add slices method
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkusFreitag committed Dec 4, 2022
1 parent 917b487 commit ba99b20
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
30 changes: 30 additions & 0 deletions object/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,36 @@ func init() {
return NIL
},
},
"slices": ObjectMethod{
Layout: MethodLayout{
ArgPattern: Args(
Arg(INTEGER_OBJ),
),
ReturnPattern: Args(
Arg(ARRAY_OBJ),
),
},
method: func(o Object, args []Object, _ Environment) Object {
ao := o.(*Array)
size := int(args[0].(*Integer).Value)
if size == 0 {
return NewError("invalid slice size, needs to be > 0")
}

length := len(ao.Elements)

slices := NewArray(make([]Object, 0))
for i := 0; i < length; i += size {
end := i + size
if end > length {
end = length
}
slices.Add(NewArray(ao.Elements[i:end]))
}

return slices
},
},
}
}

Expand Down
4 changes: 4 additions & 0 deletions object/array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ func TestArrayObjectMethods(t *testing.T) {
{`[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"]`},
{`[1,2,3,4,5,6,7,8,9].slices(3)`, `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`},
{`[1,2,3,4,5,6,7,8].slices(3)`, `[[1, 2, 3], [4, 5, 6], [7, 8]]`},
{`[1,2].slices(3)`, `[[1, 2]]`},
{`[1,2].slices(0)`, `invalid slice size, needs to be > 0`},
}

testInput(t, tests)
Expand Down

0 comments on commit ba99b20

Please sign in to comment.