From 8f3a5ba5d83dcbc5038b81806d28a69525a20407 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Sat, 4 Sep 2021 17:07:46 +0100 Subject: [PATCH] LibJS: Add Array::create_from() for generic Vector It relies on a mapper function to convert each T& to a JS::Value. This allows us to avoid awkward Vector to MarkedValueList conversion at the call site. --- Userland/Libraries/LibJS/Runtime/Array.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Userland/Libraries/LibJS/Runtime/Array.h b/Userland/Libraries/LibJS/Runtime/Array.h index 0a38828e83..703d16d6d5 100644 --- a/Userland/Libraries/LibJS/Runtime/Array.h +++ b/Userland/Libraries/LibJS/Runtime/Array.h @@ -6,6 +6,10 @@ #pragma once +#include +#include +#include +#include #include namespace JS { @@ -16,6 +20,19 @@ class Array : public Object { public: static Array* create(GlobalObject&, size_t length, Object* prototype = nullptr); static Array* create_from(GlobalObject&, Vector const&); + // Non-standard but equivalent to CreateArrayFromList. + template + static Array* create_from(GlobalObject& global_object, Vector& elements, Function 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); virtual ~Array() override;