Skip to content

Commit

Permalink
LibJS: Add spec comments to SetConstructor
Browse files Browse the repository at this point in the history
  • Loading branch information
linusg committed Apr 13, 2023
1 parent d0f80b4 commit 58566d2
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions Userland/Libraries/LibJS/Runtime/SetConstructor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,34 +37,52 @@ ThrowCompletionOr<void> SetConstructor::initialize(Realm& realm)
ThrowCompletionOr<Value> SetConstructor::call()
{
auto& vm = this->vm();

// 1. If NewTarget is undefined, throw a TypeError exception.
return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.Set);
}

// 24.2.1.1 Set ( [ iterable ] ), https://tc39.es/ecma262/#sec-set-iterable
ThrowCompletionOr<NonnullGCPtr<Object>> SetConstructor::construct(FunctionObject& new_target)
{
auto& vm = this->vm();
auto iterable = vm.argument(0);

// 2. Let set be ? OrdinaryCreateFromConstructor(NewTarget, "%Set.prototype%", « [[SetData]] »).
auto set = TRY(ordinary_create_from_constructor<Set>(vm, new_target, &Intrinsics::set_prototype));

if (vm.argument(0).is_nullish())
// 3. Set set.[[SetData]] to a new empty List.

// 4. If iterable is either undefined or null, return set.
if (iterable.is_nullish())
return set;

// 5. Let adder be ? Get(set, "add").
auto adder = TRY(set->get(vm.names.add));

// 6. If IsCallable(adder) is false, throw a TypeError exception.
if (!adder.is_function())
return vm.throw_completion<TypeError>(ErrorType::NotAFunction, "'add' property of Set");

(void)TRY(get_iterator_values(vm, vm.argument(0), [&](Value iterator_value) -> Optional<Completion> {
TRY(JS::call(vm, adder.as_function(), set, iterator_value));
// 7. Let iteratorRecord be ? GetIterator(iterable, sync).
// 8. Repeat,
// a. Let next be ? IteratorStep(iteratorRecord).
// c. Let nextValue be ? IteratorValue(next).
(void)TRY(get_iterator_values(vm, iterable, [&](Value next_value) -> Optional<Completion> {
// d. Let status be Completion(Call(adder, set, « nextValue »)).
// e. IfAbruptCloseIterator(status, iteratorRecord).
TRY(JS::call(vm, adder.as_function(), set, next_value));
return {};
}));

// b. If next is false, return set.
return set;
}

// 24.2.2.2 get Set [ @@species ], https://tc39.es/ecma262/#sec-get-set-@@species
JS_DEFINE_NATIVE_FUNCTION(SetConstructor::symbol_species_getter)
{
// 1. Return the this value.
return vm.this_value();
}

Expand Down

0 comments on commit 58566d2

Please sign in to comment.