Skip to content

Commit

Permalink
Merge pull request #177 from Flipez/array-join
Browse files Browse the repository at this point in the history
[object/array] Add ability to `.join()` elements
  • Loading branch information
Flipez authored Dec 19, 2022
2 parents 71bb1c4 + 9e5bcaa commit 143c0c3
Show file tree
Hide file tree
Showing 3 changed files with 41 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 @@ -62,6 +62,15 @@ Returns the index of the given element in the array if found. Otherwise return `
' />


### join(STRING)
> Returns `STRING`






### last()
> Returns `STRING|ARRAY|HASH|BOOLEAN|INTEGER|NIL|FUNCTION|FILE`
Expand Down
29 changes: 29 additions & 0 deletions object/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,35 @@ func (ao *Array) index(obj Object) int {

func init() {
objectMethods[ARRAY_OBJ] = map[string]ObjectMethod{
"join": ObjectMethod{
Layout: MethodLayout{
ReturnPattern: Args(
Arg(STRING_OBJ),
),
ArgPattern: Args(
OptArg(STRING_OBJ),
),
},
method: func(o Object, args []Object, _ Environment) Object {
ao := o.(*Array)
arr := make([]string, len(ao.Elements))
join := ""

if len(args) > 0 {
join = args[0].(*String).Value
}

for i, element := range ao.Elements {
if e, ok := element.(Stringable); ok {
arr[i] = e.ToStringObj(nil).Value
} else {
return NewErrorFormat("Found non stringable element %s on index %d", element.Type(), i)
}
}

return NewString(strings.Join(arr, join))
},
},
"reverse": ObjectMethod{
Layout: MethodLayout{
ReturnPattern: Args(
Expand Down
3 changes: 3 additions & 0 deletions object/array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ func TestArrayObjectMethods(t *testing.T) {
{`[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`},
{"[1,2,3,{}].join()", "Found non stringable element HASH on index 3"},
{"[1,2,3].join()", "123"},
{"[1,2,3].join('-')", "1-2-3"},
}

testInput(t, tests)
Expand Down

2 comments on commit 143c0c3

@vercel
Copy link

@vercel vercel bot commented on 143c0c3 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 143c0c3 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.