diff --git a/docs/docs/literals/array.md b/docs/docs/literals/array.md index ea6716e..950d37c 100644 --- a/docs/docs/literals/array.md +++ b/docs/docs/literals/array.md @@ -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` diff --git a/object/array.go b/object/array.go index 7c37b72..7ff6a61 100644 --- a/object/array.go +++ b/object/array.go @@ -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( diff --git a/object/array_test.go b/object/array_test.go index 4a4aee0..41502d7 100644 --- a/object/array_test.go +++ b/object/array_test.go @@ -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)