LibJS: Implement Array.prototype.{shift,pop}

This commit is contained in:
Linus Groh 2020-03-28 21:02:45 +00:00 committed by Andreas Kling
parent c5cf740830
commit c209ea1985
Notes: sideshowbarker 2024-07-19 08:05:19 +09:00
5 changed files with 66 additions and 1 deletions

View file

@ -47,6 +47,20 @@ Array::~Array()
{
}
Value Array::shift()
{
if (m_elements.size() == 0)
return js_undefined();
return Value(m_elements.take_first());
}
Value Array::pop()
{
if (m_elements.size() == 0)
return js_undefined();
return Value(m_elements.take_last());
}
void Array::push(Value value)
{
m_elements.append(value);
@ -82,5 +96,4 @@ bool Array::put_own_property(Object& this_object, const FlyString& property_name
}
return Object::put_own_property(this_object, property_name, value);
}
}

View file

@ -39,6 +39,8 @@ public:
const Vector<Value>& elements() const { return m_elements; }
Vector<Value>& elements() { return m_elements; }
Value shift();
Value pop();
void push(Value);
private:

View file

@ -35,6 +35,18 @@ namespace JS {
ArrayPrototype::ArrayPrototype()
{
put_native_function("shift", [](Object* this_object, const Vector<Value>&) -> Value {
ASSERT(this_object);
ASSERT(this_object->is_array());
return static_cast<Array*>(this_object)->shift();
});
put_native_function("pop", [](Object* this_object, const Vector<Value>&) -> Value {
ASSERT(this_object);
ASSERT(this_object->is_array());
return static_cast<Array*>(this_object)->pop();
});
put_native_function("push", [](Object* this_object, const Vector<Value>& arguments) -> Value {
if (arguments.is_empty())
return js_undefined();

View file

@ -0,0 +1,19 @@
function assert(x) { if (!x) throw 1; }
try {
var a = [1, 2, 3];
var value = a.pop();
assert(value === 3);
assert(a.length === 2);
assert(a[0] === 1);
assert(a[1] === 2);
var a = [];
var value = a.pop();
assert(value === undefined);
assert(a.length === 0);
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}

View file

@ -0,0 +1,19 @@
function assert(x) { if (!x) throw 1; }
try {
var a = [1, 2, 3];
var value = a.shift();
assert(value === 1);
assert(a.length === 2);
assert(a[0] === 2);
assert(a[1] === 3);
var a = [];
var value = a.shift();
assert(value === undefined);
assert(a.length === 0);
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}