Implemented Array.prototype.reduceRight
authorRoberto Raggi <roberto.raggi@nokia.com>
Mon, 21 May 2012 16:34:26 +0000 (18:34 +0200)
committerRoberto Raggi <roberto.raggi@nokia.com>
Mon, 21 May 2012 16:34:26 +0000 (18:34 +0200)
qv4ecmaobjects.cpp
tests/fun.4.js

index e420e27..2ab83b3 100644 (file)
@@ -1586,7 +1586,29 @@ void ArrayPrototype::method_reduceRight(Context *ctx)
 {
     Value self = ctx->thisObject;
     if (ArrayObject *instance = self.asArrayObject()) {
-        Q_UNIMPLEMENTED();
+        Value callback = ctx->argument(0);
+        Value initialValue = ctx->argument(1);
+        Value acc = initialValue;
+        for (int k = instance->value.size() - 1; k != -1; --k) {
+            Value v = instance->value.at(k);
+            if (v.isUndefined())
+                continue;
+
+            if (acc.isUndefined()) {
+                acc = v;
+                continue;
+            }
+
+            Value r;
+            Value args[4];
+            args[0] = acc;
+            args[1] = v;
+            args[2] = Value::fromNumber(k);
+            args[3] = ctx->thisObject;
+            __qmljs_call_value(ctx, &r, 0, &callback, args, 4);
+            acc = r;
+        }
+        ctx->result = acc;
     } else {
         assert(!"generic implementation");
     }
index c1b1916..b130acc 100644 (file)
@@ -13,5 +13,6 @@ print([10, 20, 30].map(function (v,k,o) { return v * v }));
 print([10, 20, 30].filter(function (v,k,o) { return v >= 20 }));
 
 print([10,20,30].reduce(function(a,v,k,o) { return a + v }));
+print([10,20,30].reduceRight(function(a,v,k,o) { return a + v }));