diff options
author | Linus Groh <mail@linusgroh.de> | 2020-05-08 16:32:56 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-05-08 20:06:49 +0200 |
commit | e333b600646fddb3e10cff44830b29cc8c90c406 (patch) | |
tree | 3f3a22c1ec826d598b85de3d99e6c5e90f45567c /Libraries/LibJS | |
parent | ca22476d9d641fc5a3def0e7de2237e8eb79015a (diff) | |
download | serenity-e333b600646fddb3e10cff44830b29cc8c90c406.zip |
LibJS: Add Array.of()
Diffstat (limited to 'Libraries/LibJS')
-rw-r--r-- | Libraries/LibJS/Runtime/ArrayConstructor.cpp | 9 | ||||
-rw-r--r-- | Libraries/LibJS/Runtime/ArrayConstructor.h | 1 | ||||
-rw-r--r-- | Libraries/LibJS/Tests/Array.of.js | 37 |
3 files changed, 47 insertions, 0 deletions
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); +} |