From f2527c8c81385c105039420a967de9110c37edc3 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Sat, 21 Jan 2023 22:34:42 -0500 Subject: [PATCH] LibJS: Add a fallible variant of Array::create_from --- Userland/Libraries/LibJS/Runtime/Array.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Userland/Libraries/LibJS/Runtime/Array.h b/Userland/Libraries/LibJS/Runtime/Array.h index 77224c4f1ba..601e90445ce 100644 --- a/Userland/Libraries/LibJS/Runtime/Array.h +++ b/Userland/Libraries/LibJS/Runtime/Array.h @@ -8,12 +8,14 @@ #pragma once #include +#include #include #include #include #include #include #include +#include namespace JS { @@ -23,6 +25,7 @@ class Array : public Object { public: static ThrowCompletionOr> create(Realm&, u64 length, Object* prototype = nullptr); static NonnullGCPtr create_from(Realm&, Vector const&); + // Non-standard but equivalent to CreateArrayFromList. template static NonnullGCPtr create_from(Realm& realm, Span elements, Function map_fn) @@ -35,6 +38,19 @@ public: return Array::create_from(realm, values); } + // Non-standard but equivalent to CreateArrayFromList. + template Callback> + static ThrowCompletionOr> try_create_from(VM& vm, Realm& realm, Span elements, Callback map_fn) + { + auto values = MarkedVector { realm.heap() }; + TRY_OR_THROW_OOM(vm, values.try_ensure_capacity(elements.size())); + + for (auto const& element : elements) + TRY_OR_THROW_OOM(vm, values.try_append(TRY(map_fn(element)))); + + return Array::create_from(realm, values); + } + virtual ~Array() override = default; virtual ThrowCompletionOr> internal_get_own_property(PropertyKey const&) const override;