Selaa lähdekoodia

LibJS: Add Array.prototype.reverse

Kesse Jones 5 vuotta sitten
vanhempi
commit
df6696f576

+ 22 - 0
Libraries/LibJS/Runtime/ArrayPrototype.cpp

@@ -54,6 +54,7 @@ ArrayPrototype::ArrayPrototype()
     put_native_function("concat", concat, 1);
     put_native_function("slice", slice, 2);
     put_native_function("indexOf", index_of, 1);
+    put_native_function("reverse", reverse, 0);
     put("length", Value(0));
 }
 
@@ -343,4 +344,25 @@ Value ArrayPrototype::index_of(Interpreter& interpreter)
 
     return Value(-1);
 }
+
+Value ArrayPrototype::reverse(Interpreter& interpreter)
+{
+    auto* array = array_from(interpreter);
+    if (!array)
+        return {};
+
+    if (array->elements().size() == 0)
+        return array;
+
+    Vector<Value> array_reverse;
+    array_reverse.ensure_capacity(array->elements().size());
+
+    for (ssize_t i = array->elements().size() - 1; i >= 0; --i)
+        array_reverse.append(array->elements().at(i));
+
+    array->elements() = move(array_reverse);
+
+    return array;
+}
+
 }

+ 1 - 0
Libraries/LibJS/Runtime/ArrayPrototype.h

@@ -51,5 +51,6 @@ private:
     static Value concat(Interpreter&);
     static Value slice(Interpreter&);
     static Value index_of(Interpreter&);
+    static Value reverse(Interpreter&);
 };
 }

+ 31 - 0
Libraries/LibJS/Tests/Array.prototype.reverse.js

@@ -0,0 +1,31 @@
+load("test-common.js");
+
+try {
+    assert(Array.prototype.reverse.length === 0);
+
+    var array = [1, 2, 3];
+    
+    assert(array[0] === 1);
+    assert(array[1] === 2);
+    assert(array[2] === 3);
+    
+    array.reverse();
+    
+    assert(array[0] === 3);
+    assert(array[1] === 2);
+    assert(array[2] === 1);
+    
+    var array_ref = array.reverse();
+    
+    assert(array_ref[0] === 1);
+    assert(array_ref[1] === 2);
+    assert(array_ref[2] === 3);
+
+    assert(array[0] === 1);
+    assert(array[1] === 2);
+    assert(array[2] === 3);
+
+    console.log("PASS");
+} catch (e) {
+    console.log("FAIL: " + e);
+}