From a7b21ec0f4a77e6e7cdf2b57f9255a02539b02f4 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 5 Apr 2020 18:06:27 +0200 Subject: [PATCH] LibJS: Add Array.prototype.toString() --- Libraries/LibJS/Runtime/ArrayPrototype.cpp | 30 +++++++++++++++++++ Libraries/LibJS/Runtime/ArrayPrototype.h | 1 + .../LibJS/Tests/Array.prototype.toString.js | 9 ++++++ 3 files changed, 40 insertions(+) create mode 100644 Libraries/LibJS/Tests/Array.prototype.toString.js diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 23a807d0a67..8a295e96a32 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -25,10 +25,12 @@ */ #include +#include #include #include #include #include +#include #include namespace JS { @@ -38,6 +40,7 @@ ArrayPrototype::ArrayPrototype() put_native_function("shift", shift); put_native_function("pop", pop); put_native_function("push", push, 1); + put_native_function("toString", to_string, 0); put("length", Value(0)); } @@ -45,6 +48,18 @@ ArrayPrototype::~ArrayPrototype() { } +static Array* array_from(Interpreter& interpreter) +{ + auto* this_object = interpreter.this_value().to_object(interpreter.heap()); + if (!this_object) + return {}; + if (!this_object->is_array()) { + interpreter.throw_exception("TypeError", "Not an Array"); + return nullptr; + } + return static_cast(this_object); +} + Value ArrayPrototype::push(Interpreter& interpreter) { auto* this_object = interpreter.this_value().to_object(interpreter.heap()); @@ -75,4 +90,19 @@ Value ArrayPrototype::shift(Interpreter& interpreter) return static_cast(this_object)->shift(); } +Value ArrayPrototype::to_string(Interpreter& interpreter) +{ + auto* array = array_from(interpreter); + if (!array) + return {}; + + StringBuilder builder; + for (size_t i = 0; i < array->elements().size(); ++i) { + if (i != 0) + builder.append(','); + builder.append(array->elements()[i].to_string()); + } + return js_string(interpreter, builder.to_string()); +} + } diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.h b/Libraries/LibJS/Runtime/ArrayPrototype.h index 9828512b610..bed19807a56 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.h +++ b/Libraries/LibJS/Runtime/ArrayPrototype.h @@ -41,6 +41,7 @@ private: static Value push(Interpreter&); static Value shift(Interpreter&); static Value pop(Interpreter&); + static Value to_string(Interpreter&); }; } diff --git a/Libraries/LibJS/Tests/Array.prototype.toString.js b/Libraries/LibJS/Tests/Array.prototype.toString.js new file mode 100644 index 00000000000..e9ace65d26e --- /dev/null +++ b/Libraries/LibJS/Tests/Array.prototype.toString.js @@ -0,0 +1,9 @@ +try { + var a = [1, 2, 3]; + assert(a.toString() === '1,2,3'); + assert([].toString() === ''); + assert([5].toString() === '5'); + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}