MapConstructor.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Jint.Collections;
  2. using Jint.Native.Function;
  3. using Jint.Native.Iterator;
  4. using Jint.Native.Object;
  5. using Jint.Native.Symbol;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. using Jint.Runtime.Interop;
  9. namespace Jint.Native.Map
  10. {
  11. public sealed class MapConstructor : FunctionInstance, IConstructor
  12. {
  13. private static readonly JsString _functionName = new JsString("Map");
  14. private MapConstructor(Engine engine)
  15. : base(engine, _functionName)
  16. {
  17. }
  18. public MapPrototype PrototypeObject { get; private set; }
  19. public static MapConstructor CreateMapConstructor(Engine engine)
  20. {
  21. var obj = new MapConstructor(engine)
  22. {
  23. _prototype = engine.Function.PrototypeObject
  24. };
  25. // The value of the [[Prototype]] internal property of the Map constructor is the Function prototype object
  26. obj.PrototypeObject = MapPrototype.CreatePrototypeObject(engine, obj);
  27. obj._length = new PropertyDescriptor(0, PropertyFlag.Configurable);
  28. // The initial value of Map.prototype is the Map prototype object
  29. obj._prototypeDescriptor = new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden);
  30. return obj;
  31. }
  32. protected override void Initialize()
  33. {
  34. var symbols = new SymbolDictionary(1)
  35. {
  36. [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(get: new ClrFunctionInstance(_engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined, PropertyFlag.Configurable)
  37. };
  38. SetSymbols(symbols);
  39. }
  40. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  41. {
  42. return thisObject;
  43. }
  44. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  45. {
  46. if (thisObject.IsUndefined())
  47. {
  48. ExceptionHelper.ThrowTypeError(_engine, "Constructor Map requires 'new'");
  49. }
  50. return Construct(arguments, thisObject);
  51. }
  52. /// <summary>
  53. /// https://tc39.es/ecma262/#sec-map-iterable
  54. /// </summary>
  55. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  56. {
  57. if (newTarget.IsUndefined())
  58. {
  59. ExceptionHelper.ThrowTypeError(_engine);
  60. }
  61. var map = OrdinaryCreateFromConstructor(newTarget, PrototypeObject, static (engine, _) => new MapInstance(engine));
  62. if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined())
  63. {
  64. var adder = map.Get("set");
  65. var iterator = arguments.At(0).GetIterator(_engine);
  66. IteratorProtocol.AddEntriesFromIterable(map, iterator, adder);
  67. }
  68. return map;
  69. }
  70. }
  71. }