From 29253bf93252392ce284be7b503f036333f94342 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Mon, 13 Apr 2020 16:46:27 +0100 Subject: [PATCH] LibJS: Add Array.prototype.unshift() --- Libraries/LibJS/Runtime/ArrayPrototype.cpp | 11 +++++++ Libraries/LibJS/Runtime/ArrayPrototype.h | 1 + .../LibJS/Tests/Array.prototype.unshift.js | 30 +++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 Libraries/LibJS/Tests/Array.prototype.unshift.js diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index a5e52642dbf..4b8e338c6d4 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -41,6 +41,7 @@ ArrayPrototype::ArrayPrototype() put_native_function("push", push, 1); put_native_function("shift", shift, 0); put_native_function("toString", to_string, 0); + put_native_function("unshift", unshift, 1); put("length", Value(0)); } @@ -70,6 +71,16 @@ Value ArrayPrototype::push(Interpreter& interpreter) return Value(array->length()); } +Value ArrayPrototype::unshift(Interpreter& interpreter) +{ + auto* array = array_from(interpreter); + if (!array) + return {}; + for (size_t i = 0; i < interpreter.argument_count(); ++i) + array->elements().insert(i, interpreter.argument(i)); + return Value(array->length()); +} + Value ArrayPrototype::pop(Interpreter& interpreter) { auto* array = array_from(interpreter); diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.h b/Libraries/LibJS/Runtime/ArrayPrototype.h index d4df4858ff6..653ff885f56 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.h +++ b/Libraries/LibJS/Runtime/ArrayPrototype.h @@ -42,6 +42,7 @@ private: static Value push(Interpreter&); static Value shift(Interpreter&); static Value to_string(Interpreter&); + static Value unshift(Interpreter&); }; } diff --git a/Libraries/LibJS/Tests/Array.prototype.unshift.js b/Libraries/LibJS/Tests/Array.prototype.unshift.js new file mode 100644 index 00000000000..3bae2736b17 --- /dev/null +++ b/Libraries/LibJS/Tests/Array.prototype.unshift.js @@ -0,0 +1,30 @@ +load("test-common.js"); + +try { + assert(Array.prototype.unshift.length === 1); + + var a = ["hello"]; + var length = a.unshift(); + assert(length === 1); + assert(a.length === 1); + assert(a[0] === "hello"); + + length = a.unshift("friends"); + assert(length === 2); + assert(a.length === 2); + assert(a[0] === "friends"); + assert(a[1] === "hello"); + + length = a.unshift(1, 2, 3); + assert(length === 5); + assert(a.length === 5); + assert(a[0] === 1); + assert(a[1] === 2); + assert(a[2] === 3); + assert(a[3] === "friends"); + assert(a[4] === "hello"); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}