From df6696f5762a8cdd31ab225f8e71ddd12b593722 Mon Sep 17 00:00:00 2001 From: Kesse Jones Date: Mon, 20 Apr 2020 10:39:39 -0300 Subject: LibJS: Add Array.prototype.reverse --- Libraries/LibJS/Runtime/ArrayPrototype.cpp | 22 +++++++++++++++++ Libraries/LibJS/Runtime/ArrayPrototype.h | 1 + Libraries/LibJS/Tests/Array.prototype.reverse.js | 31 ++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 Libraries/LibJS/Tests/Array.prototype.reverse.js diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index d3e881d81d..c063085419 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/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 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; +} + } diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.h b/Libraries/LibJS/Runtime/ArrayPrototype.h index 50afdced8b..168827dcb5 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.h +++ b/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&); }; } diff --git a/Libraries/LibJS/Tests/Array.prototype.reverse.js b/Libraries/LibJS/Tests/Array.prototype.reverse.js new file mode 100644 index 0000000000..2b782fa154 --- /dev/null +++ b/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); +} -- cgit v1.2.3