From e333b600646fddb3e10cff44830b29cc8c90c406 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Fri, 8 May 2020 16:32:56 +0100 Subject: LibJS: Add Array.of() --- Libraries/LibJS/Runtime/ArrayConstructor.cpp | 9 +++++++ Libraries/LibJS/Runtime/ArrayConstructor.h | 1 + Libraries/LibJS/Tests/Array.of.js | 37 ++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 Libraries/LibJS/Tests/Array.of.js (limited to 'Libraries/LibJS') diff --git a/Libraries/LibJS/Runtime/ArrayConstructor.cpp b/Libraries/LibJS/Runtime/ArrayConstructor.cpp index 003171de39..3c5b7c07b6 100644 --- a/Libraries/LibJS/Runtime/ArrayConstructor.cpp +++ b/Libraries/LibJS/Runtime/ArrayConstructor.cpp @@ -44,6 +44,7 @@ ArrayConstructor::ArrayConstructor() u8 attr = Attribute::Writable | Attribute::Configurable; put_native_function("isArray", is_array, 1, attr); + put_native_function("of", of, 0, attr); } ArrayConstructor::~ArrayConstructor() @@ -86,4 +87,12 @@ Value ArrayConstructor::is_array(Interpreter& interpreter) return Value(StringView(value.as_object().class_name()) == "Array"); } +Value ArrayConstructor::of(Interpreter& interpreter) +{ + auto* array = Array::create(interpreter.global_object()); + for (size_t i = 0; i < interpreter.argument_count(); ++i) + array->elements().append(interpreter.argument(i)); + return array; +} + } diff --git a/Libraries/LibJS/Runtime/ArrayConstructor.h b/Libraries/LibJS/Runtime/ArrayConstructor.h index a038d080e4..14e5f30665 100644 --- a/Libraries/LibJS/Runtime/ArrayConstructor.h +++ b/Libraries/LibJS/Runtime/ArrayConstructor.h @@ -43,6 +43,7 @@ private: virtual const char* class_name() const override { return "ArrayConstructor"; } static Value is_array(Interpreter&); + static Value of(Interpreter&); }; } diff --git a/Libraries/LibJS/Tests/Array.of.js b/Libraries/LibJS/Tests/Array.of.js new file mode 100644 index 0000000000..1fb4200847 --- /dev/null +++ b/Libraries/LibJS/Tests/Array.of.js @@ -0,0 +1,37 @@ +load("test-common.js"); + +try { + assert(Array.of.length === 0); + + assert(typeof Array.of() === "object"); + + var a; + + a = Array.of(5); + assert(a.length === 1); + assert(a[0] === 5); + + a = Array.of("5"); + assert(a.length === 1); + assert(a[0] === "5"); + + a = Array.of(Infinity); + assert(a.length === 1); + assert(a[0] === Infinity); + + a = Array.of(1, 2, 3); + assert(a.length === 3); + assert(a[0] === 1); + assert(a[1] === 2); + assert(a[2] === 3); + + a = Array.of([1, 2, 3]); + assert(a.length === 1); + assert(a[0][0] === 1); + assert(a[0][1] === 2); + assert(a[0][2] === 3); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +} -- cgit v1.2.3