MapConstructor.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. internal MapConstructor(
  15. Engine engine,
  16. Realm realm,
  17. FunctionPrototype functionPrototype,
  18. ObjectPrototype objectPrototype)
  19. : base(engine, realm, _functionName)
  20. {
  21. _prototype = functionPrototype;
  22. PrototypeObject = new MapPrototype(engine, realm, this, objectPrototype);
  23. _length = new PropertyDescriptor(0, PropertyFlag.Configurable);
  24. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  25. }
  26. public MapPrototype PrototypeObject { get; private set; }
  27. protected override void Initialize()
  28. {
  29. var symbols = new SymbolDictionary(1)
  30. {
  31. [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(get: new ClrFunctionInstance(_engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined, PropertyFlag.Configurable)
  32. };
  33. SetSymbols(symbols);
  34. }
  35. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  36. {
  37. return thisObject;
  38. }
  39. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  40. {
  41. ExceptionHelper.ThrowTypeError(_realm, "Constructor Map requires 'new'");
  42. return null;
  43. }
  44. /// <summary>
  45. /// https://tc39.es/ecma262/#sec-map-iterable
  46. /// </summary>
  47. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget)
  48. {
  49. if (newTarget.IsUndefined())
  50. {
  51. ExceptionHelper.ThrowTypeError(_realm);
  52. }
  53. var map = OrdinaryCreateFromConstructor(
  54. newTarget,
  55. static intrinsics => intrinsics.Map.PrototypeObject,
  56. static (engine, realm, _) => new MapInstance(engine, realm));
  57. if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined())
  58. {
  59. var adder = map.Get("set");
  60. var iterator = arguments.At(0).GetIterator(_realm);
  61. IteratorProtocol.AddEntriesFromIterable(map, iterator, adder);
  62. }
  63. return map;
  64. }
  65. }
  66. }