diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 23a807d0a6..8a295e96a3 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 9828512b61..bed19807a5 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 0000000000..e9ace65d26 --- /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); +}