BooleanConstructor.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2020, Jack Karamanian <karamanian.jack@gmail.com>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/BooleanConstructor.h>
  9. #include <LibJS/Runtime/BooleanObject.h>
  10. #include <LibJS/Runtime/GlobalObject.h>
  11. namespace JS {
  12. BooleanConstructor::BooleanConstructor(Realm& realm)
  13. : NativeFunction(realm.vm().names.Boolean.as_string(), realm.intrinsics().function_prototype())
  14. {
  15. }
  16. ThrowCompletionOr<void> BooleanConstructor::initialize(Realm& realm)
  17. {
  18. auto& vm = this->vm();
  19. MUST_OR_THROW_OOM(NativeFunction::initialize(realm));
  20. // 20.3.2.1 Boolean.prototype, https://tc39.es/ecma262/#sec-boolean.prototype
  21. define_direct_property(vm.names.prototype, realm.intrinsics().boolean_prototype(), 0);
  22. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  23. return {};
  24. }
  25. // 20.3.1.1 Boolean ( value ), https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  26. ThrowCompletionOr<Value> BooleanConstructor::call()
  27. {
  28. auto& vm = this->vm();
  29. auto value = vm.argument(0);
  30. // 1. Let b be ToBoolean(value).
  31. auto b = value.to_boolean();
  32. // 2. If NewTarget is undefined, return b.
  33. return Value(b);
  34. }
  35. // 20.3.1.1 Boolean ( value ), https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  36. ThrowCompletionOr<NonnullGCPtr<Object>> BooleanConstructor::construct(FunctionObject& new_target)
  37. {
  38. auto& vm = this->vm();
  39. auto value = vm.argument(0);
  40. // 1. Let b be ToBoolean(value).
  41. auto b = value.to_boolean();
  42. // 3. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] »).
  43. // 4. Set O.[[BooleanData]] to b.
  44. // 5. Return O.
  45. return TRY(ordinary_create_from_constructor<BooleanObject>(vm, new_target, &Intrinsics::boolean_prototype, b));
  46. }
  47. }