WeakMapInstance.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. namespace Jint.Native.WeakMap
  5. {
  6. public class WeakMapInstance : ObjectInstance
  7. {
  8. private readonly ConditionalWeakTable<JsValue, JsValue> _table;
  9. public WeakMapInstance(Engine engine) : base(engine)
  10. {
  11. _table = new ConditionalWeakTable<JsValue, JsValue>();
  12. }
  13. internal bool WeakMapHas(JsValue key)
  14. {
  15. return _table.TryGetValue(key, out _);
  16. }
  17. internal bool WeakMapDelete(JsValue key)
  18. {
  19. return _table.Remove(key);
  20. }
  21. internal void WeakMapSet(JsValue key, JsValue value)
  22. {
  23. if (key.IsPrimitive())
  24. {
  25. ExceptionHelper.ThrowTypeError(_engine.Realm, "WeakMap key must be an object, got " + key.ToString());
  26. }
  27. #if NETSTANDARD2_1
  28. _table.AddOrUpdate(key, value);
  29. #else
  30. _table.Remove(key);
  31. _table.Add(key, value);
  32. #endif
  33. }
  34. internal JsValue WeakMapGet(JsValue key)
  35. {
  36. if (!_table.TryGetValue(key, out var value))
  37. {
  38. return Undefined;
  39. }
  40. return value;
  41. }
  42. }
  43. }