mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-06-09 09:34:57 +09:00
LibJS: Add Array.prototype.toString()
This commit is contained in:
parent
2c4a5849f6
commit
a7b21ec0f4
Notes:
sideshowbarker
2024-07-19 07:52:53 +09:00
Author: https://github.com/awesomekling
Commit: a7b21ec0f4
3 changed files with 40 additions and 0 deletions
|
@ -25,10 +25,12 @@
|
|||
*/
|
||||
|
||||
#include <AK/Function.h>
|
||||
#include <AK/StringBuilder.h>
|
||||
#include <LibJS/Heap/Heap.h>
|
||||
#include <LibJS/Interpreter.h>
|
||||
#include <LibJS/Runtime/Array.h>
|
||||
#include <LibJS/Runtime/ArrayPrototype.h>
|
||||
#include <LibJS/Runtime/Error.h>
|
||||
#include <LibJS/Runtime/Value.h>
|
||||
|
||||
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<Error>("TypeError", "Not an Array");
|
||||
return nullptr;
|
||||
}
|
||||
return static_cast<Array*>(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<Array*>(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());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -41,6 +41,7 @@ private:
|
|||
static Value push(Interpreter&);
|
||||
static Value shift(Interpreter&);
|
||||
static Value pop(Interpreter&);
|
||||
static Value to_string(Interpreter&);
|
||||
};
|
||||
|
||||
}
|
||||
|
|
9
Libraries/LibJS/Tests/Array.prototype.toString.js
Normal file
9
Libraries/LibJS/Tests/Array.prototype.toString.js
Normal file
|
@ -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);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue