BooleanConstructor.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. void BooleanConstructor::initialize(Realm& realm)
  17. {
  18. auto& vm = this->vm();
  19. Base::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. }
  24. // 20.3.1.1 Boolean ( value ), https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  25. ThrowCompletionOr<Value> BooleanConstructor::call()
  26. {
  27. auto& vm = this->vm();
  28. auto value = vm.argument(0);
  29. // 1. Let b be ToBoolean(value).
  30. auto b = value.to_boolean();
  31. // 2. If NewTarget is undefined, return b.
  32. return Value(b);
  33. }
  34. // 20.3.1.1 Boolean ( value ), https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  35. ThrowCompletionOr<NonnullGCPtr<Object>> BooleanConstructor::construct(FunctionObject& new_target)
  36. {
  37. auto& vm = this->vm();
  38. auto value = vm.argument(0);
  39. // 1. Let b be ToBoolean(value).
  40. auto b = value.to_boolean();
  41. // 3. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] »).
  42. // 4. Set O.[[BooleanData]] to b.
  43. // 5. Return O.
  44. return TRY(ordinary_create_from_constructor<BooleanObject>(vm, new_target, &Intrinsics::boolean_prototype, b));
  45. }
  46. }