diff --git a/doc/7-configuring-icinga-2.md b/doc/7-configuring-icinga-2.md index 58824c3ba..c12c2f29b 100644 --- a/doc/7-configuring-icinga-2.md +++ b/doc/7-configuring-icinga-2.md @@ -941,6 +941,33 @@ Signature: Returns a copy of the string. +### Array type + +#### Array#add +#### Array#clear +#### Array#clone +#### Array#contains +#### Array#len +#### Array#remove +#### Array#set +#### Array#sort + +Signature: + + function sort(less_cmp); + +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. + +### Dictionary type + +#### Dictionary#clone +#### Dictionary#contains +#### Dictionary#len +#### Dictionary#remove +#### Dictionary#set + ### ScriptFunction type #### ScriptFunction#call diff --git a/lib/base/array-script.cpp b/lib/base/array-script.cpp index 751c552d3..46f020a03 100644 --- a/lib/base/array-script.cpp +++ b/lib/base/array-script.cpp @@ -21,6 +21,7 @@ #include "base/scriptfunction.hpp" #include "base/scriptfunctionwrapper.hpp" #include "base/scriptframe.hpp" +#include "base/objectlock.hpp" using namespace icinga; @@ -66,6 +67,32 @@ static void ArrayClear(void) self->Clear(); } +static bool ArraySortCmp(const ScriptFunction::Ptr& cmp, const Value& a, const Value& b) +{ + std::vector args; + args.push_back(a); + args.push_back(b); + return cmp->Invoke(args); +} + +static Array::Ptr ArraySort(const std::vector& args) +{ + ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); + Array::Ptr self = static_cast(vframe->Self); + + Array::Ptr arr = self->ShallowClone(); + + if (args.empty()) { + ObjectLock olock(arr); + std::sort(arr->Begin(), arr->End()); + } else { + ObjectLock olock(arr); + std::sort(arr->Begin(), arr->End(), boost::bind(ArraySortCmp, args[0], _1, _2)); + } + + return arr; +} + static Array::Ptr ArrayClone(void) { ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); @@ -85,6 +112,7 @@ Object::Ptr Array::GetPrototype(void) prototype->Set("remove", new ScriptFunction(WrapScriptFunction(ArrayRemove))); prototype->Set("contains", new ScriptFunction(WrapScriptFunction(ArrayContains))); prototype->Set("clear", new ScriptFunction(WrapScriptFunction(ArrayClear))); + prototype->Set("sort", new ScriptFunction(WrapScriptFunction(ArraySort))); prototype->Set("clone", new ScriptFunction(WrapScriptFunction(ArrayClone))); }