diff options
author | Linus Groh <mail@linusgroh.de> | 2021-09-04 17:07:46 +0100 |
---|---|---|
committer | Linus Groh <mail@linusgroh.de> | 2021-09-04 19:08:18 +0100 |
commit | 8f3a5ba5d83dcbc5038b81806d28a69525a20407 (patch) | |
tree | 72896175e3a808edd8bde57b215ba74f7c61d575 /Userland/Libraries/LibJS/Runtime | |
parent | e7e2ccc04c8f93ada63815ef4d06470f9dd62fa0 (diff) | |
download | serenity-8f3a5ba5d83dcbc5038b81806d28a69525a20407.zip |
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.
Diffstat (limited to 'Userland/Libraries/LibJS/Runtime')
-rw-r--r-- | Userland/Libraries/LibJS/Runtime/Array.h | 17 |
1 files changed, 17 insertions, 0 deletions
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 <AK/Assertions.h> +#include <AK/Function.h> +#include <AK/Vector.h> +#include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Object.h> 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<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); virtual ~Array() override; |