WeakSetPrototype.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma warning disable CA1859 // Use concrete types when possible for improved performance -- most of prototype methods return JsValue
  2. using Jint.Collections;
  3. using Jint.Native.Object;
  4. using Jint.Native.Symbol;
  5. using Jint.Runtime;
  6. using Jint.Runtime.Descriptors;
  7. using Jint.Runtime.Interop;
  8. namespace Jint.Native.WeakSet;
  9. /// <summary>
  10. /// https://tc39.es/ecma262/#sec-weakset-objects
  11. /// </summary>
  12. internal sealed class WeakSetPrototype : Prototype
  13. {
  14. private readonly WeakSetConstructor _constructor;
  15. internal ClrFunction _originalAddFunction = null!;
  16. internal WeakSetPrototype(
  17. Engine engine,
  18. Realm realm,
  19. WeakSetConstructor constructor,
  20. ObjectPrototype prototype) : base(engine, realm)
  21. {
  22. _prototype = prototype;
  23. _constructor = constructor;
  24. }
  25. protected override void Initialize()
  26. {
  27. _originalAddFunction = new ClrFunction(Engine, "add", Add, 1, PropertyFlag.Configurable);
  28. const PropertyFlag PropertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable;
  29. var properties = new PropertyDictionary(5, checkExistingKeys: false)
  30. {
  31. ["length"] = new(0, PropertyFlag.Configurable),
  32. ["constructor"] = new(_constructor, PropertyFlag.NonEnumerable),
  33. ["delete"] = new(new ClrFunction(Engine, "delete", Delete, 1, PropertyFlag.Configurable), PropertyFlags),
  34. ["add"] = new(_originalAddFunction, PropertyFlags),
  35. ["has"] = new(new ClrFunction(Engine, "has", Has, 1, PropertyFlag.Configurable), PropertyFlags),
  36. };
  37. SetProperties(properties);
  38. var symbols = new SymbolDictionary(1)
  39. {
  40. [GlobalSymbolRegistry.ToStringTag] = new("WeakSet", false, false, true)
  41. };
  42. SetSymbols(symbols);
  43. }
  44. private JsValue Add(JsValue thisObject, JsValue[] arguments)
  45. {
  46. var set = AssertWeakSetInstance(thisObject);
  47. set.WeakSetAdd(arguments.At(0));
  48. return thisObject;
  49. }
  50. private JsValue Delete(JsValue thisObject, JsValue[] arguments)
  51. {
  52. var set = AssertWeakSetInstance(thisObject);
  53. return set.WeakSetDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False;
  54. }
  55. private JsValue Has(JsValue thisObject, JsValue[] arguments)
  56. {
  57. var set = AssertWeakSetInstance(thisObject);
  58. return set.WeakSetHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False;
  59. }
  60. private JsWeakSet AssertWeakSetInstance(JsValue thisObject)
  61. {
  62. if (thisObject is JsWeakSet set)
  63. {
  64. return set;
  65. }
  66. ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakSet");
  67. return default;
  68. }
  69. }