Implement the Array#sort method

refs #8069
This commit is contained in:
Gunnar Beutner 2015-01-20 16:56:08 +01:00
parent 0c1bf72f6f
commit 604b080c59
2 changed files with 55 additions and 0 deletions

View File

@ -941,6 +941,33 @@ Signature:
Returns a copy of the string.
### <a id="array-type"> Array type
#### <a id="array-add"> Array#add
#### <a id="array-clear"> Array#clear
#### <a id="array-clone"> Array#clone
#### <a id="array-contains"> Array#contains
#### <a id="array-len"> Array#len
#### <a id="array-remove"> Array#remove
#### <a id="array-set"> Array#set
#### <a id="array-sort"> 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.
### <a id="dictionary-type"> Dictionary type
#### <a id="dictionary-clone"> Dictionary#clone
#### <a id="dictionary-contains"> Dictionary#contains
#### <a id="dictionary-len"> Dictionary#len
#### <a id="dictionary-remove"> Dictionary#remove
#### <a id="dictionary-set"> Dictionary#set
### <a id="scriptfunction-type"> ScriptFunction type
#### <a id="scriptfunction-call"> ScriptFunction#call

View File

@ -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<Value> args;
args.push_back(a);
args.push_back(b);
return cmp->Invoke(args);
}
static Array::Ptr ArraySort(const std::vector<Value>& args)
{
ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
Array::Ptr self = static_cast<Array::Ptr>(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)));
}