mirror of
https://github.com/RGBCube/serenity
synced 2025-07-25 19:37:35 +00:00
LibJS: Add Array::create_from() for generic Vector<T>
It relies on a mapper function to convert each T& to a JS::Value. This allows us to avoid awkward Vector<T> to MarkedValueList conversion at the call site.
This commit is contained in:
parent
e7e2ccc04c
commit
8f3a5ba5d8
1 changed files with 17 additions and 0 deletions
|
@ -6,6 +6,10 @@
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <AK/Assertions.h>
|
||||||
|
#include <AK/Function.h>
|
||||||
|
#include <AK/Vector.h>
|
||||||
|
#include <LibJS/Runtime/GlobalObject.h>
|
||||||
#include <LibJS/Runtime/Object.h>
|
#include <LibJS/Runtime/Object.h>
|
||||||
|
|
||||||
namespace JS {
|
namespace JS {
|
||||||
|
@ -16,6 +20,19 @@ class Array : public Object {
|
||||||
public:
|
public:
|
||||||
static Array* create(GlobalObject&, size_t length, Object* prototype = nullptr);
|
static Array* create(GlobalObject&, size_t length, Object* prototype = nullptr);
|
||||||
static Array* create_from(GlobalObject&, Vector<Value> const&);
|
static Array* create_from(GlobalObject&, Vector<Value> const&);
|
||||||
|
// Non-standard but equivalent to CreateArrayFromList.
|
||||||
|
template<typename T>
|
||||||
|
static Array* create_from(GlobalObject& global_object, Vector<T>& elements, Function<Value(T&)> map_fn)
|
||||||
|
{
|
||||||
|
auto& vm = global_object.vm();
|
||||||
|
auto values = MarkedValueList { global_object.heap() };
|
||||||
|
values.ensure_capacity(elements.size());
|
||||||
|
for (auto& element : elements) {
|
||||||
|
values.append(map_fn(element));
|
||||||
|
VERIFY(!vm.exception());
|
||||||
|
}
|
||||||
|
return Array::create_from(global_object, values);
|
||||||
|
}
|
||||||
|
|
||||||
explicit Array(Object& prototype);
|
explicit Array(Object& prototype);
|
||||||
virtual ~Array() override;
|
virtual ~Array() override;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue