diff --git a/doc/16-library-reference.md b/doc/16-library-reference.md index 45dd32744..f14829f05 100644 --- a/doc/16-library-reference.md +++ b/doc/16-library-reference.md @@ -417,6 +417,14 @@ Returns a copy of the array where all items are sorted. The items are compared using the `<` (less-than) operator. A custom comparator function can be specified with the `less_cmp` argument. +### Array#join + +Signature: + + function join(separator); + +Joins all elements of the array using the specified separator. + ## Dictionary type ### Dictionary#clone diff --git a/lib/base/array-script.cpp b/lib/base/array-script.cpp index 265899c0e..6118d11b4 100644 --- a/lib/base/array-script.cpp +++ b/lib/base/array-script.cpp @@ -22,6 +22,7 @@ #include "base/functionwrapper.hpp" #include "base/scriptframe.hpp" #include "base/objectlock.hpp" +#include using namespace icinga; @@ -100,6 +101,28 @@ static Array::Ptr ArrayClone(void) return self->ShallowClone(); } +static Value ArrayJoin(const Value& separator) +{ + ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); + Array::Ptr self = static_cast(vframe->Self); + + Value result; + bool first = true; + + ObjectLock olock(self); + BOOST_FOREACH(const Value& item, self) { + if (first) { + first = false; + } else { + result = result + separator; + } + + result = result + item; + } + + return result; +} + Object::Ptr Array::GetPrototype(void) { static Dictionary::Ptr prototype; @@ -114,6 +137,7 @@ Object::Ptr Array::GetPrototype(void) prototype->Set("clear", new Function(WrapFunction(ArrayClear))); prototype->Set("sort", new Function(WrapFunction(ArraySort))); prototype->Set("clone", new Function(WrapFunction(ArrayClone))); + prototype->Set("join", new Function(WrapFunction(ArrayJoin))); } return prototype;