BooleanConstructor.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #include <LibJS/Runtime/ValueInlines.h>
  12. namespace JS {
  13. BooleanConstructor::BooleanConstructor(Realm& realm)
  14. : NativeFunction(realm.vm().names.Boolean.as_string(), realm.intrinsics().function_prototype())
  15. {
  16. }
  17. void BooleanConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. Base::initialize(realm);
  21. // 20.3.2.1 Boolean.prototype, https://tc39.es/ecma262/#sec-boolean.prototype
  22. define_direct_property(vm.names.prototype, realm.intrinsics().boolean_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  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. }