1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-30 23:08:11 +00:00

LibJS: Add Array.of()

This commit is contained in:
Linus Groh 2020-05-08 16:32:56 +01:00 committed by Andreas Kling
parent ca22476d9d
commit e333b60064
3 changed files with 47 additions and 0 deletions

View file

@ -44,6 +44,7 @@ ArrayConstructor::ArrayConstructor()
u8 attr = Attribute::Writable | Attribute::Configurable; u8 attr = Attribute::Writable | Attribute::Configurable;
put_native_function("isArray", is_array, 1, attr); put_native_function("isArray", is_array, 1, attr);
put_native_function("of", of, 0, attr);
} }
ArrayConstructor::~ArrayConstructor() ArrayConstructor::~ArrayConstructor()
@ -86,4 +87,12 @@ Value ArrayConstructor::is_array(Interpreter& interpreter)
return Value(StringView(value.as_object().class_name()) == "Array"); 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;
}
} }

View file

@ -43,6 +43,7 @@ private:
virtual const char* class_name() const override { return "ArrayConstructor"; } virtual const char* class_name() const override { return "ArrayConstructor"; }
static Value is_array(Interpreter&); static Value is_array(Interpreter&);
static Value of(Interpreter&);
}; };
} }

View file

@ -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);
}