ArrayPrototype.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Jint.Collections;
  5. using Jint.Native.Iterator;
  6. using Jint.Native.Number;
  7. using Jint.Native.Object;
  8. using Jint.Native.Symbol;
  9. using Jint.Pooling;
  10. using Jint.Runtime;
  11. using Jint.Runtime.Descriptors;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native.Array
  14. {
  15. /// <summary>
  16. /// https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object
  17. /// </summary>
  18. public sealed class ArrayPrototype : ArrayInstance
  19. {
  20. private readonly Realm _realm;
  21. private readonly ArrayConstructor _constructor;
  22. internal ClrFunctionInstance _originalIteratorFunction;
  23. internal ArrayPrototype(
  24. Engine engine,
  25. Realm realm,
  26. ArrayConstructor arrayConstructor,
  27. ObjectPrototype objectPrototype) : base(engine)
  28. {
  29. _prototype = objectPrototype;
  30. _length = new PropertyDescriptor(JsNumber.PositiveZero, PropertyFlag.Writable);
  31. _realm = realm;
  32. _constructor = arrayConstructor;
  33. }
  34. protected override void Initialize()
  35. {
  36. var unscopables = new ObjectInstance(_engine)
  37. {
  38. _prototype = null
  39. };
  40. unscopables.SetDataProperty("at", JsBoolean.True);
  41. unscopables.SetDataProperty("copyWithin", JsBoolean.True);
  42. unscopables.SetDataProperty("entries", JsBoolean.True);
  43. unscopables.SetDataProperty("fill", JsBoolean.True);
  44. unscopables.SetDataProperty("find", JsBoolean.True);
  45. unscopables.SetDataProperty("findIndex", JsBoolean.True);
  46. unscopables.SetDataProperty("flat", JsBoolean.True);
  47. unscopables.SetDataProperty("flatMap", JsBoolean.True);
  48. unscopables.SetDataProperty("includes", JsBoolean.True);
  49. unscopables.SetDataProperty("keys", JsBoolean.True);
  50. unscopables.SetDataProperty("values", JsBoolean.True);
  51. const PropertyFlag propertyFlags = PropertyFlag.Writable | PropertyFlag.Configurable;
  52. var properties = new PropertyDictionary(32, checkExistingKeys: false)
  53. {
  54. ["constructor"] = new PropertyDescriptor(_constructor, PropertyFlag.NonEnumerable),
  55. ["toString"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toString", ToString, 0, PropertyFlag.Configurable), propertyFlags),
  56. ["toLocaleString"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toLocaleString", ToLocaleString, 0, PropertyFlag.Configurable), propertyFlags),
  57. ["concat"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "concat", Concat, 1, PropertyFlag.Configurable), propertyFlags),
  58. ["copyWithin"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "copyWithin", CopyWithin, 2, PropertyFlag.Configurable), propertyFlags),
  59. ["entries"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "entries", Entries, 0, PropertyFlag.Configurable), propertyFlags),
  60. ["fill"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "fill", Fill, 1, PropertyFlag.Configurable), propertyFlags),
  61. ["join"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "join", Join, 1, PropertyFlag.Configurable), propertyFlags),
  62. ["pop"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "pop", Pop, 0, PropertyFlag.Configurable), propertyFlags),
  63. ["push"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "push", Push, 1, PropertyFlag.Configurable), propertyFlags),
  64. ["reverse"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "reverse", Reverse, 0, PropertyFlag.Configurable), propertyFlags),
  65. ["shift"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "shift", Shift, 0, PropertyFlag.Configurable), propertyFlags),
  66. ["slice"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "slice", Slice, 2, PropertyFlag.Configurable), propertyFlags),
  67. ["sort"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "sort", Sort, 1, PropertyFlag.Configurable), propertyFlags),
  68. ["splice"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "splice", Splice, 2, PropertyFlag.Configurable), propertyFlags),
  69. ["unshift"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "unshift", Unshift, 1, PropertyFlag.Configurable), propertyFlags),
  70. ["includes"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "includes", Includes, 1, PropertyFlag.Configurable), propertyFlags),
  71. ["indexOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "indexOf", IndexOf, 1, PropertyFlag.Configurable), propertyFlags),
  72. ["lastIndexOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "lastIndexOf", LastIndexOf, 1, PropertyFlag.Configurable), propertyFlags),
  73. ["every"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "every", Every, 1, PropertyFlag.Configurable), propertyFlags),
  74. ["some"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "some", Some, 1, PropertyFlag.Configurable), propertyFlags),
  75. ["forEach"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "forEach", ForEach, 1, PropertyFlag.Configurable), propertyFlags),
  76. ["map"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "map", Map, 1, PropertyFlag.Configurable), propertyFlags),
  77. ["filter"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "filter", Filter, 1, PropertyFlag.Configurable), propertyFlags),
  78. ["reduce"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "reduce", Reduce, 1, PropertyFlag.Configurable), propertyFlags),
  79. ["reduceRight"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "reduceRight", ReduceRight, 1, PropertyFlag.Configurable), propertyFlags),
  80. ["find"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "find", Find, 1, PropertyFlag.Configurable), propertyFlags),
  81. ["findIndex"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "findIndex", FindIndex, 1, PropertyFlag.Configurable), propertyFlags),
  82. ["keys"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "keys", Keys, 0, PropertyFlag.Configurable), propertyFlags),
  83. ["values"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "values", Values, 0, PropertyFlag.Configurable), propertyFlags),
  84. ["flat"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "flat", Flat, 0, PropertyFlag.Configurable), propertyFlags),
  85. ["flatMap"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "flatMap", FlatMap, 1, PropertyFlag.Configurable), propertyFlags),
  86. ["at"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "at", At, 1, PropertyFlag.Configurable), propertyFlags),
  87. };
  88. SetProperties(properties);
  89. _originalIteratorFunction = new ClrFunctionInstance(Engine, "iterator", Values, 1);
  90. var symbols = new SymbolDictionary(2)
  91. {
  92. [GlobalSymbolRegistry.Iterator] = new PropertyDescriptor(_originalIteratorFunction, propertyFlags),
  93. [GlobalSymbolRegistry.Unscopables] = new PropertyDescriptor(unscopables, PropertyFlag.Configurable)
  94. };
  95. SetSymbols(symbols);
  96. }
  97. private ObjectInstance Keys(JsValue thisObj, JsValue[] arguments)
  98. {
  99. if (thisObj is ObjectInstance oi && oi.IsArrayLike)
  100. {
  101. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.Key);
  102. }
  103. ExceptionHelper.ThrowTypeError(_realm, "cannot construct iterator");
  104. return null;
  105. }
  106. internal ObjectInstance Values(JsValue thisObj, JsValue[] arguments)
  107. {
  108. if (thisObj is ObjectInstance oi && oi.IsArrayLike)
  109. {
  110. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.Value);
  111. }
  112. ExceptionHelper.ThrowTypeError(_realm, "cannot construct iterator");
  113. return null;
  114. }
  115. private ObjectInstance Entries(JsValue thisObj, JsValue[] arguments)
  116. {
  117. if (thisObj is ObjectInstance oi && oi.IsArrayLike)
  118. {
  119. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.KeyAndValue);
  120. }
  121. ExceptionHelper.ThrowTypeError(_realm, "cannot construct iterator");
  122. return null;
  123. }
  124. /// <summary>
  125. /// https://tc39.es/ecma262/#sec-array.prototype.fill
  126. /// </summary>
  127. private JsValue Fill(JsValue thisObj, JsValue[] arguments)
  128. {
  129. var o = TypeConverter.ToObject(_realm, thisObj);
  130. var operations = ArrayOperations.For(o);
  131. var length = operations.GetLongLength();
  132. var value = arguments.At(0);
  133. var start = ConvertAndCheckForInfinity(arguments.At(1), 0);
  134. var relativeStart = TypeConverter.ToInteger(start);
  135. ulong actualStart;
  136. if (relativeStart < 0)
  137. {
  138. actualStart = (ulong) System.Math.Max(length + relativeStart, 0);
  139. }
  140. else
  141. {
  142. actualStart = (ulong) System.Math.Min(relativeStart, length);
  143. }
  144. var end = ConvertAndCheckForInfinity(arguments.At(2), (long) length);
  145. var relativeEnd = TypeConverter.ToInteger(end);
  146. ulong actualEnd;
  147. if (relativeEnd < 0)
  148. {
  149. actualEnd = (ulong) System.Math.Max(length + relativeEnd, 0);
  150. }
  151. else
  152. {
  153. actualEnd = (ulong) System.Math.Min(relativeEnd, length);
  154. }
  155. for (var i = actualStart; i < actualEnd; ++i)
  156. {
  157. operations.Set(i, value, throwOnError: false);
  158. }
  159. return o;
  160. }
  161. /// <summary>
  162. /// https://tc39.es/ecma262/#sec-array.prototype.copywithin
  163. /// </summary>
  164. private JsValue CopyWithin(JsValue thisObj, JsValue[] arguments)
  165. {
  166. var o = TypeConverter.ToObject(_realm, thisObj);
  167. JsValue target = arguments.At(0);
  168. JsValue start = arguments.At(1);
  169. JsValue end = arguments.At(2);
  170. var operations = ArrayOperations.For(o);
  171. var initialLength = operations.GetLongLength();
  172. var len = ConvertAndCheckForInfinity(initialLength, 0);
  173. var relativeTarget = ConvertAndCheckForInfinity(target, 0);
  174. var to = relativeTarget < 0 ?
  175. System.Math.Max(len + relativeTarget, 0) :
  176. System.Math.Min(relativeTarget, len);
  177. var relativeStart = ConvertAndCheckForInfinity(start, 0);
  178. var from = relativeStart < 0 ?
  179. System.Math.Max(len + relativeStart, 0) :
  180. System.Math.Min(relativeStart, len);
  181. var relativeEnd = ConvertAndCheckForInfinity(end, len);
  182. var final = relativeEnd < 0 ?
  183. System.Math.Max(len + relativeEnd, 0) :
  184. System.Math.Min(relativeEnd, len);
  185. var count = System.Math.Min(final - from, len - to);
  186. long direction = 1;
  187. if (from < to && to < from + count)
  188. {
  189. direction = -1;
  190. from += count - 1;
  191. to += count - 1;
  192. }
  193. while (count > 0)
  194. {
  195. var fromPresent = operations.HasProperty((ulong) from);
  196. if (fromPresent)
  197. {
  198. var fromValue = operations.Get((ulong) from);
  199. operations.Set((ulong) to, fromValue, throwOnError: true);
  200. }
  201. else
  202. {
  203. operations.DeletePropertyOrThrow((ulong) to);
  204. }
  205. from += direction;
  206. to += direction;
  207. count--;
  208. }
  209. return o;
  210. }
  211. static long ConvertAndCheckForInfinity(JsValue jsValue, long defaultValue)
  212. {
  213. if (jsValue.IsUndefined())
  214. {
  215. return defaultValue;
  216. }
  217. var num = TypeConverter.ToNumber(jsValue);
  218. if (double.IsPositiveInfinity(num))
  219. {
  220. return long.MaxValue;
  221. }
  222. return (long) num;
  223. }
  224. /// <summary>
  225. /// https://tc39.es/ecma262/#sec-array.prototype.lastindexof
  226. /// </summary>
  227. private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments)
  228. {
  229. var o = ArrayOperations.For(_realm, thisObj);
  230. var len = o.GetLongLength();
  231. if (len == 0)
  232. {
  233. return JsNumber.IntegerNegativeOne;
  234. }
  235. var n = arguments.Length > 1
  236. ? TypeConverter.ToInteger(arguments[1])
  237. : len - 1;
  238. double k;
  239. if (n >= 0)
  240. {
  241. k = System.Math.Min(n, len - 1); // min
  242. }
  243. else
  244. {
  245. k = len - System.Math.Abs(n);
  246. }
  247. if (k < 0 || k > ArrayOperations.MaxArrayLikeLength)
  248. {
  249. return JsNumber.IntegerNegativeOne;
  250. }
  251. var searchElement = arguments.At(0);
  252. var i = (ulong) k;
  253. for (; ; i--)
  254. {
  255. var kPresent = o.HasProperty(i);
  256. if (kPresent)
  257. {
  258. var elementK = o.Get(i);
  259. if (elementK == searchElement)
  260. {
  261. return i;
  262. }
  263. }
  264. if (i == 0)
  265. {
  266. break;
  267. }
  268. }
  269. return JsNumber.IntegerNegativeOne;
  270. }
  271. /// <summary>
  272. /// https://tc39.es/ecma262/#sec-array.prototype.reduce
  273. /// </summary>
  274. private JsValue Reduce(JsValue thisObj, JsValue[] arguments)
  275. {
  276. var callbackfn = arguments.At(0);
  277. var initialValue = arguments.At(1);
  278. var o = ArrayOperations.For(_realm, thisObj);
  279. var len = o.GetLength();
  280. var callable = GetCallable(callbackfn);
  281. if (len == 0 && arguments.Length < 2)
  282. {
  283. ExceptionHelper.ThrowTypeError(_realm);
  284. }
  285. var k = 0;
  286. JsValue accumulator = Undefined;
  287. if (arguments.Length > 1)
  288. {
  289. accumulator = initialValue;
  290. }
  291. else
  292. {
  293. var kPresent = false;
  294. while (kPresent == false && k < len)
  295. {
  296. if (kPresent = o.TryGetValue((uint) k, out var temp))
  297. {
  298. accumulator = temp;
  299. }
  300. k++;
  301. }
  302. if (kPresent == false)
  303. {
  304. ExceptionHelper.ThrowTypeError(_realm);
  305. }
  306. }
  307. var args = new JsValue[4];
  308. args[3] = o.Target;
  309. while (k < len)
  310. {
  311. var i = (uint) k;
  312. if (o.TryGetValue(i, out var kvalue))
  313. {
  314. args[0] = accumulator;
  315. args[1] = kvalue;
  316. args[2] = i;
  317. accumulator = callable.Call(Undefined, args);
  318. }
  319. k++;
  320. }
  321. return accumulator;
  322. }
  323. /// <summary>
  324. /// https://tc39.es/ecma262/#sec-array.prototype.filter
  325. /// </summary>
  326. private JsValue Filter(JsValue thisObj, JsValue[] arguments)
  327. {
  328. var callbackfn = arguments.At(0);
  329. var thisArg = arguments.At(1);
  330. var o = ArrayOperations.For(_realm, thisObj);
  331. var len = o.GetLength();
  332. var callable = GetCallable(callbackfn);
  333. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), 0);
  334. var operations = ArrayOperations.For(a);
  335. uint to = 0;
  336. var args = _engine._jsValueArrayPool.RentArray(3);
  337. args[2] = o.Target;
  338. for (uint k = 0; k < len; k++)
  339. {
  340. if (o.TryGetValue(k, out var kvalue))
  341. {
  342. args[0] = kvalue;
  343. args[1] = k;
  344. var selected = callable.Call(thisArg, args);
  345. if (TypeConverter.ToBoolean(selected))
  346. {
  347. operations.CreateDataPropertyOrThrow(to, kvalue);
  348. to++;
  349. }
  350. }
  351. }
  352. operations.SetLength(to);
  353. _engine._jsValueArrayPool.ReturnArray(args);
  354. return a;
  355. }
  356. /// <summary>
  357. /// https://tc39.es/ecma262/#sec-array.prototype.map
  358. /// </summary>
  359. private JsValue Map(JsValue thisObj, JsValue[] arguments)
  360. {
  361. if (thisObj is ArrayInstance arrayInstance && !arrayInstance.HasOwnProperty(CommonProperties.Constructor))
  362. {
  363. return arrayInstance.Map(arguments);
  364. }
  365. var o = ArrayOperations.For(_realm, thisObj);
  366. var len = o.GetLongLength();
  367. if (len > ArrayOperations.MaxArrayLength)
  368. {
  369. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");;
  370. }
  371. var callbackfn = arguments.At(0);
  372. var thisArg = arguments.At(1);
  373. var callable = GetCallable(callbackfn);
  374. var a = ArrayOperations.For(_realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), (uint) len));
  375. var args = _engine._jsValueArrayPool.RentArray(3);
  376. args[2] = o.Target;
  377. for (uint k = 0; k < len; k++)
  378. {
  379. if (o.TryGetValue(k, out var kvalue))
  380. {
  381. args[0] = kvalue;
  382. args[1] = k;
  383. var mappedValue = callable.Call(thisArg, args);
  384. a.CreateDataPropertyOrThrow(k, mappedValue);
  385. }
  386. }
  387. _engine._jsValueArrayPool.ReturnArray(args);
  388. return a.Target;
  389. }
  390. /// <summary>
  391. /// https://tc39.es/ecma262/#sec-array.prototype.flat
  392. /// </summary>
  393. private JsValue Flat(JsValue thisObj, JsValue[] arguments)
  394. {
  395. var O = TypeConverter.ToObject(_realm, thisObj);
  396. var operations = ArrayOperations.For(O);
  397. var sourceLen = operations.GetLength();
  398. double depthNum = 1;
  399. var depth = arguments.At(0);
  400. if (!depth.IsUndefined())
  401. {
  402. depthNum = TypeConverter.ToIntegerOrInfinity(depth);
  403. }
  404. if (depthNum < 0)
  405. {
  406. depthNum = 0;
  407. }
  408. var A = _realm.Intrinsics.Array.ArraySpeciesCreate(O, 0);
  409. FlattenIntoArray(A, O, sourceLen, 0, depthNum);
  410. return A;
  411. }
  412. /// <summary>
  413. /// https://tc39.es/ecma262/#sec-array.prototype.flatmap
  414. /// </summary>
  415. private JsValue FlatMap(JsValue thisObj, JsValue[] arguments)
  416. {
  417. var O = TypeConverter.ToObject(_realm, thisObj);
  418. var mapperFunction = arguments.At(0);
  419. var thisArg = arguments.At(1);
  420. var sourceLen = O.Length;
  421. if (!mapperFunction.IsCallable)
  422. {
  423. ExceptionHelper.ThrowTypeError(_realm, "flatMap mapper function is not callable");
  424. }
  425. var A = _realm.Intrinsics.Array.ArraySpeciesCreate(O, 0);
  426. FlattenIntoArray(A, O, sourceLen, 0, 1, (ICallable) mapperFunction, thisArg);
  427. return A;
  428. }
  429. /// <summary>
  430. /// https://tc39.es/ecma262/#sec-flattenintoarray
  431. /// </summary>
  432. private long FlattenIntoArray(
  433. ObjectInstance target,
  434. ObjectInstance source,
  435. uint sourceLen,
  436. long start,
  437. double depth,
  438. ICallable mapperFunction = null,
  439. JsValue thisArg = null)
  440. {
  441. var targetIndex = start;
  442. var sourceIndex = 0;
  443. var callArguments = System.Array.Empty<JsValue>();
  444. if (mapperFunction is not null)
  445. {
  446. callArguments = _engine._jsValueArrayPool.RentArray(3);
  447. callArguments[2] = source;
  448. }
  449. while (sourceIndex < sourceLen)
  450. {
  451. var P = TypeConverter.ToString(sourceIndex);
  452. var exists = source.HasProperty(P);
  453. if (exists)
  454. {
  455. var element = source.Get(P);
  456. if (mapperFunction is not null)
  457. {
  458. callArguments[0] = element;
  459. callArguments[1] = JsNumber.Create(sourceIndex);
  460. element = mapperFunction.Call(thisArg, callArguments);
  461. }
  462. var shouldFlatten = false;
  463. if (depth > 0)
  464. {
  465. shouldFlatten = element.IsArray();
  466. }
  467. if (shouldFlatten)
  468. {
  469. var newDepth = double.IsPositiveInfinity(depth)
  470. ? depth
  471. : depth - 1;
  472. var objectInstance = (ObjectInstance) element;
  473. var elementLen = objectInstance.Length;
  474. targetIndex = FlattenIntoArray(target, objectInstance, elementLen, targetIndex, newDepth);
  475. }
  476. else
  477. {
  478. if (targetIndex >= NumberConstructor.MaxSafeInteger)
  479. {
  480. ExceptionHelper.ThrowTypeError(_realm);
  481. }
  482. target.CreateDataPropertyOrThrow(targetIndex, element);
  483. targetIndex += 1;
  484. }
  485. }
  486. sourceIndex++;
  487. }
  488. if (mapperFunction is not null)
  489. {
  490. _engine._jsValueArrayPool.ReturnArray(callArguments);
  491. }
  492. return targetIndex;
  493. }
  494. private JsValue ForEach(JsValue thisObj, JsValue[] arguments)
  495. {
  496. var callbackfn = arguments.At(0);
  497. var thisArg = arguments.At(1);
  498. var o = ArrayOperations.For(_realm, thisObj);
  499. var len = o.GetLength();
  500. var callable = GetCallable(callbackfn);
  501. var args = _engine._jsValueArrayPool.RentArray(3);
  502. args[2] = o.Target;
  503. for (uint k = 0; k < len; k++)
  504. {
  505. if (o.TryGetValue(k, out var kvalue))
  506. {
  507. args[0] = kvalue;
  508. args[1] = k;
  509. callable.Call(thisArg, args);
  510. }
  511. }
  512. _engine._jsValueArrayPool.ReturnArray(args);
  513. return Undefined;
  514. }
  515. private JsValue Includes(JsValue thisObj, JsValue[] arguments)
  516. {
  517. var o = ArrayOperations.For(_realm, thisObj);
  518. var len = o.GetLongLength();
  519. if (len == 0)
  520. {
  521. return false;
  522. }
  523. var searchElement = arguments.At(0);
  524. var fromIndex = arguments.At(1, 0);
  525. var n = TypeConverter.ToNumber(fromIndex);
  526. n = n > ArrayOperations.MaxArrayLikeLength
  527. ? ArrayOperations.MaxArrayLikeLength
  528. : n;
  529. var k = (ulong) System.Math.Max(
  530. n >= 0
  531. ? n
  532. : len - System.Math.Abs(n), 0);
  533. while (k < len)
  534. {
  535. var value = o.Get(k);
  536. if (SameValueZeroComparer.Equals(value, searchElement))
  537. {
  538. return true;
  539. }
  540. k++;
  541. }
  542. return false;
  543. }
  544. private JsValue Some(JsValue thisObj, JsValue[] arguments)
  545. {
  546. var target = TypeConverter.ToObject(_realm, thisObj);
  547. return target.FindWithCallback(arguments, out _, out _, false);
  548. }
  549. private JsValue Every(JsValue thisObj, JsValue[] arguments)
  550. {
  551. var o = ArrayOperations.For(_realm, thisObj);
  552. ulong len = o.GetLongLength();
  553. if (len == 0)
  554. {
  555. return JsBoolean.True;
  556. }
  557. var callbackfn = arguments.At(0);
  558. var thisArg = arguments.At(1);
  559. var callable = GetCallable(callbackfn);
  560. var args = _engine._jsValueArrayPool.RentArray(3);
  561. args[2] = o.Target;
  562. for (uint k = 0; k < len; k++)
  563. {
  564. if (o.TryGetValue(k, out var kvalue))
  565. {
  566. args[0] = kvalue;
  567. args[1] = k;
  568. var testResult = callable.Call(thisArg, args);
  569. if (false == TypeConverter.ToBoolean(testResult))
  570. {
  571. return JsBoolean.False;
  572. }
  573. }
  574. }
  575. _engine._jsValueArrayPool.ReturnArray(args);
  576. return JsBoolean.True;
  577. }
  578. private JsValue IndexOf(JsValue thisObj, JsValue[] arguments)
  579. {
  580. var o = ArrayOperations.For(_realm, thisObj);
  581. var len = o.GetLongLength();
  582. if (len == 0)
  583. {
  584. return -1;
  585. }
  586. var startIndex = arguments.Length > 1
  587. ? TypeConverter.ToNumber(arguments[1])
  588. : 0;
  589. if (startIndex > ArrayOperations.MaxArrayLikeLength)
  590. {
  591. return JsNumber.IntegerNegativeOne;
  592. }
  593. ulong k;
  594. if (startIndex < 0)
  595. {
  596. var abs = System.Math.Abs(startIndex);
  597. ulong temp = len - (uint) abs;
  598. if (abs > len || temp < 0)
  599. {
  600. temp = 0;
  601. }
  602. k = temp;
  603. }
  604. else
  605. {
  606. k = (ulong) startIndex;
  607. }
  608. if (k >= len)
  609. {
  610. return -1;
  611. }
  612. ulong smallestIndex = o.GetSmallestIndex(len);
  613. if (smallestIndex > k)
  614. {
  615. k = smallestIndex;
  616. }
  617. var searchElement = arguments.At(0);
  618. for (; k < len; k++)
  619. {
  620. var kPresent = o.HasProperty(k);
  621. if (kPresent)
  622. {
  623. var elementK = o.Get(k);
  624. if (elementK == searchElement)
  625. {
  626. return k;
  627. }
  628. }
  629. }
  630. return -1;
  631. }
  632. private JsValue Find(JsValue thisObj, JsValue[] arguments)
  633. {
  634. var target = TypeConverter.ToObject(_realm, thisObj);
  635. target.FindWithCallback(arguments, out _, out var value, true);
  636. return value;
  637. }
  638. private JsValue FindIndex(JsValue thisObj, JsValue[] arguments)
  639. {
  640. var target = TypeConverter.ToObject(_realm, thisObj);
  641. if (target.FindWithCallback(arguments, out var index, out _, true))
  642. {
  643. return index;
  644. }
  645. return -1;
  646. }
  647. /// <summary>
  648. /// https://tc39.es/proposal-relative-indexing-method/#sec-array-prototype-additions
  649. /// </summary>
  650. private JsValue At(JsValue thisObj, JsValue[] arguments)
  651. {
  652. var target = TypeConverter.ToObject(_realm, thisObj);
  653. var len = target.Length;
  654. var relativeIndex = TypeConverter.ToInteger(arguments.At(0));
  655. ulong actualIndex;
  656. if (relativeIndex < 0)
  657. {
  658. actualIndex = (ulong) (len + relativeIndex);
  659. }
  660. else
  661. {
  662. actualIndex = (ulong) relativeIndex;
  663. }
  664. if (actualIndex < 0 || actualIndex >= len)
  665. {
  666. return Undefined;
  667. }
  668. return target.Get(actualIndex);
  669. }
  670. /// <summary>
  671. /// https://tc39.es/ecma262/#sec-array.prototype.splice
  672. /// </summary>
  673. private JsValue Splice(JsValue thisObj, JsValue[] arguments)
  674. {
  675. var start = arguments.At(0);
  676. var deleteCount = arguments.At(1);
  677. var obj = TypeConverter.ToObject(_realm, thisObj);
  678. var o = ArrayOperations.For(_realm, obj);
  679. var len = o.GetLongLength();
  680. var relativeStart = TypeConverter.ToInteger(start);
  681. ulong actualStart;
  682. if (relativeStart < 0)
  683. {
  684. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  685. }
  686. else
  687. {
  688. actualStart = (ulong) System.Math.Min(relativeStart, len);
  689. }
  690. var items = System.Array.Empty<JsValue>();
  691. ulong insertCount;
  692. ulong actualDeleteCount;
  693. if (arguments.Length == 0)
  694. {
  695. insertCount = 0;
  696. actualDeleteCount = 0;
  697. }
  698. else if (arguments.Length == 1)
  699. {
  700. insertCount = 0;
  701. actualDeleteCount = len - actualStart;
  702. }
  703. else
  704. {
  705. insertCount = (ulong) (arguments.Length - 2);
  706. var dc = TypeConverter.ToInteger(deleteCount);
  707. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc,0), len - actualStart);
  708. items = System.Array.Empty<JsValue>();
  709. if (arguments.Length > 2)
  710. {
  711. items = new JsValue[arguments.Length - 2];
  712. System.Array.Copy(arguments, 2, items, 0, items.Length);
  713. }
  714. }
  715. if (len + insertCount - actualDeleteCount > ArrayOperations.MaxArrayLikeLength)
  716. {
  717. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  718. }
  719. var instance = _realm.Intrinsics.Array.ArraySpeciesCreate(obj, actualDeleteCount);
  720. var a = ArrayOperations.For(instance);
  721. for (uint k = 0; k < actualDeleteCount; k++)
  722. {
  723. var index = actualStart + k;
  724. if (o.HasProperty(index))
  725. {
  726. var fromValue = o.Get(index);
  727. a.CreateDataPropertyOrThrow(k, fromValue);
  728. }
  729. }
  730. a.SetLength((uint) actualDeleteCount);
  731. var length = len - actualDeleteCount + (uint) items.Length;
  732. o.EnsureCapacity(length);
  733. if ((ulong) items.Length < actualDeleteCount)
  734. {
  735. for (ulong k = actualStart; k < len - actualDeleteCount; k++)
  736. {
  737. var from = k + actualDeleteCount;
  738. var to = k + (ulong) items.Length;
  739. if (o.HasProperty(from))
  740. {
  741. var fromValue = o.Get(from);
  742. o.Set(to, fromValue, throwOnError: false);
  743. }
  744. else
  745. {
  746. o.DeletePropertyOrThrow(to);
  747. }
  748. }
  749. for (var k = len; k > len - actualDeleteCount + (ulong) items.Length; k--)
  750. {
  751. o.DeletePropertyOrThrow(k - 1);
  752. }
  753. }
  754. else if ((ulong) items.Length > actualDeleteCount)
  755. {
  756. for (var k = len - actualDeleteCount; k > actualStart; k--)
  757. {
  758. var from = k + actualDeleteCount - 1;
  759. var to = k + (ulong) items.Length - 1;
  760. if (o.HasProperty(from))
  761. {
  762. var fromValue = o.Get(from);
  763. o.Set(to, fromValue, throwOnError: true);
  764. }
  765. else
  766. {
  767. o.DeletePropertyOrThrow(to);
  768. }
  769. }
  770. }
  771. for (uint k = 0; k < items.Length; k++)
  772. {
  773. var e = items[k];
  774. o.Set(k + actualStart, e, throwOnError: true);
  775. }
  776. o.SetLength(length);
  777. return a.Target;
  778. }
  779. private JsValue Unshift(JsValue thisObj, JsValue[] arguments)
  780. {
  781. var o = ArrayOperations.For(_realm, thisObj);
  782. var len = o.GetLongLength();
  783. var argCount = (uint) arguments.Length;
  784. if (len + argCount > ArrayOperations.MaxArrayLikeLength)
  785. {
  786. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  787. }
  788. o.EnsureCapacity(len + argCount);
  789. var minIndex = o.GetSmallestIndex(len);
  790. for (var k = len; k > minIndex; k--)
  791. {
  792. var from = k - 1;
  793. var to = k + argCount - 1;
  794. if (o.TryGetValue(from, out var fromValue))
  795. {
  796. o.Set(to, fromValue, true);
  797. }
  798. else
  799. {
  800. o.DeletePropertyOrThrow(to);
  801. }
  802. }
  803. for (uint j = 0; j < argCount; j++)
  804. {
  805. o.Set(j, arguments[j], true);
  806. }
  807. o.SetLength(len + argCount);
  808. return len + argCount;
  809. }
  810. /// <summary>
  811. /// https://tc39.es/ecma262/#sec-array.prototype.sort
  812. /// </summary>
  813. private JsValue Sort(JsValue thisObj, JsValue[] arguments)
  814. {
  815. var obj = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObj));
  816. var compareArg = arguments.At(0);
  817. ICallable compareFn = null;
  818. if (!compareArg.IsUndefined())
  819. {
  820. if (compareArg is not ICallable callable)
  821. {
  822. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  823. return null;
  824. }
  825. compareFn = callable;
  826. }
  827. var len = obj.GetLength();
  828. if (len <= 1)
  829. {
  830. return obj.Target;
  831. }
  832. var items = new List<JsValue>((int) System.Math.Min(10_000, obj.GetLength()));
  833. for (ulong k = 0; k < len; ++k)
  834. {
  835. if (obj.TryGetValue(k, out var kValue))
  836. {
  837. items.Add(kValue);
  838. }
  839. }
  840. var itemCount = items.Count;
  841. // don't eat inner exceptions
  842. try
  843. {
  844. var array = items.OrderBy(x => x, ArrayComparer.WithFunction(_engine, compareFn)).ToArray();
  845. uint j;
  846. for (j = 0; j < itemCount; ++j)
  847. {
  848. if (!ReferenceEquals(array[j], null))
  849. {
  850. obj.Set(j, array[j], throwOnError: true);
  851. }
  852. }
  853. for (; j < len; ++j)
  854. {
  855. obj.DeletePropertyOrThrow(j);
  856. }
  857. }
  858. catch (InvalidOperationException e)
  859. {
  860. throw e.InnerException ?? e;
  861. }
  862. return obj.Target;
  863. }
  864. /// <summary>
  865. /// https://tc39.es/ecma262/#sec-array.prototype.slice
  866. /// </summary>
  867. private JsValue Slice(JsValue thisObj, JsValue[] arguments)
  868. {
  869. var start = arguments.At(0);
  870. var end = arguments.At(1);
  871. var o = ArrayOperations.For(_realm, thisObj);
  872. var len = o.GetLongLength();
  873. var relativeStart = TypeConverter.ToInteger(start);
  874. ulong k;
  875. if (relativeStart < 0)
  876. {
  877. k = (ulong) System.Math.Max(len + relativeStart, 0);
  878. }
  879. else
  880. {
  881. k = (ulong) System.Math.Min(TypeConverter.ToInteger(start), len);
  882. }
  883. ulong final;
  884. if (end.IsUndefined())
  885. {
  886. final = (ulong) TypeConverter.ToNumber(len);
  887. }
  888. else
  889. {
  890. double relativeEnd = TypeConverter.ToInteger(end);
  891. if (relativeEnd < 0)
  892. {
  893. final = (ulong) System.Math.Max(len + relativeEnd, 0);
  894. }
  895. else
  896. {
  897. final = (ulong) System.Math.Min(relativeEnd, len);
  898. }
  899. }
  900. if (k < final && final - k > ArrayOperations.MaxArrayLength)
  901. {
  902. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");;
  903. }
  904. var length = (uint) System.Math.Max(0, (long) final - (long) k);
  905. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), length);
  906. if (thisObj is ArrayInstance ai && a is ArrayInstance a2)
  907. {
  908. a2.CopyValues(ai, (uint) k, 0, length);
  909. }
  910. else
  911. {
  912. // slower path
  913. var operations = ArrayOperations.For(a);
  914. for (uint n = 0; k < final; k++, n++)
  915. {
  916. if (o.TryGetValue(k, out var kValue))
  917. {
  918. operations.CreateDataPropertyOrThrow(n, kValue);
  919. }
  920. }
  921. }
  922. a.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(length, PropertyFlag.ConfigurableEnumerableWritable));
  923. return a;
  924. }
  925. private JsValue Shift(JsValue thisObj, JsValue[] arg2)
  926. {
  927. var o = ArrayOperations.For(_realm, thisObj);
  928. var len = o.GetLength();
  929. if (len == 0)
  930. {
  931. o.SetLength(0);
  932. return Undefined;
  933. }
  934. var first = o.Get(0);
  935. for (uint k = 1; k < len; k++)
  936. {
  937. var to = k - 1;
  938. if (o.TryGetValue(k, out var fromVal))
  939. {
  940. o.Set(to, fromVal, throwOnError: false);
  941. }
  942. else
  943. {
  944. o.DeletePropertyOrThrow(to);
  945. }
  946. }
  947. o.DeletePropertyOrThrow(len - 1);
  948. o.SetLength(len - 1);
  949. return first;
  950. }
  951. /// <summary>
  952. /// https://tc39.es/ecma262/#sec-array.prototype.reverse
  953. /// </summary>
  954. private JsValue Reverse(JsValue thisObj, JsValue[] arguments)
  955. {
  956. var o = ArrayOperations.For(_realm, thisObj);
  957. var len = o.GetLongLength();
  958. var middle = (ulong) System.Math.Floor(len / 2.0);
  959. uint lower = 0;
  960. while (lower != middle)
  961. {
  962. var upper = len - lower - 1;
  963. var lowerExists = o.HasProperty(lower);
  964. var lowerValue = lowerExists ? o.Get(lower) : null;
  965. var upperExists = o.HasProperty(upper);
  966. var upperValue = upperExists ? o.Get(upper) : null;
  967. if (lowerExists && upperExists)
  968. {
  969. o.Set(lower, upperValue, throwOnError: true);
  970. o.Set(upper, lowerValue, throwOnError: true);
  971. }
  972. if (!lowerExists && upperExists)
  973. {
  974. o.Set(lower, upperValue, throwOnError: true);
  975. o.DeletePropertyOrThrow(upper);
  976. }
  977. if (lowerExists && !upperExists)
  978. {
  979. o.DeletePropertyOrThrow(lower);
  980. o.Set(upper, lowerValue, throwOnError: true);
  981. }
  982. lower++;
  983. }
  984. return o.Target;
  985. }
  986. internal JsValue Join(JsValue thisObj, JsValue[] arguments)
  987. {
  988. var separator = arguments.At(0);
  989. var o = ArrayOperations.For(_realm, thisObj);
  990. var len = o.GetLength();
  991. var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
  992. // as per the spec, this has to be called after ToString(separator)
  993. if (len == 0)
  994. {
  995. return JsString.Empty;
  996. }
  997. static string StringFromJsValue(JsValue value)
  998. {
  999. return value.IsNullOrUndefined()
  1000. ? ""
  1001. : TypeConverter.ToString(value);
  1002. }
  1003. var s = StringFromJsValue(o.Get(0));
  1004. if (len == 1)
  1005. {
  1006. return s;
  1007. }
  1008. using var sb = StringBuilderPool.Rent();
  1009. sb.Builder.Append(s);
  1010. for (uint k = 1; k < len; k++)
  1011. {
  1012. sb.Builder.Append(sep);
  1013. sb.Builder.Append(StringFromJsValue(o.Get(k)));
  1014. }
  1015. return sb.ToString();
  1016. }
  1017. private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments)
  1018. {
  1019. var array = ArrayOperations.For(_realm, thisObj);
  1020. var len = array.GetLength();
  1021. const string separator = ",";
  1022. if (len == 0)
  1023. {
  1024. return JsString.Empty;
  1025. }
  1026. JsValue r;
  1027. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1028. {
  1029. r = JsString.Empty;
  1030. }
  1031. else
  1032. {
  1033. var elementObj = TypeConverter.ToObject(_realm, firstElement);
  1034. var func = elementObj.Get("toLocaleString", elementObj) as ICallable;
  1035. if (func is null)
  1036. {
  1037. ExceptionHelper.ThrowTypeError(_realm);
  1038. }
  1039. r = func.Call(elementObj, Arguments.Empty);
  1040. }
  1041. for (uint k = 1; k < len; k++)
  1042. {
  1043. string s = r + separator;
  1044. if (!array.TryGetValue(k, out var nextElement) || nextElement.IsNull())
  1045. {
  1046. r = JsString.Empty;
  1047. }
  1048. else
  1049. {
  1050. var elementObj = TypeConverter.ToObject(_realm, nextElement);
  1051. var func = elementObj.Get("toLocaleString", elementObj) as ICallable;
  1052. if (func is null)
  1053. {
  1054. ExceptionHelper.ThrowTypeError(_realm);
  1055. }
  1056. r = func.Call(elementObj, Arguments.Empty);
  1057. }
  1058. r = s + r;
  1059. }
  1060. return r;
  1061. }
  1062. /// <summary>
  1063. /// https://tc39.es/ecma262/#sec-array.prototype.concat
  1064. /// </summary>
  1065. private JsValue Concat(JsValue thisObj, JsValue[] arguments)
  1066. {
  1067. var o = TypeConverter.ToObject(_realm, thisObj);
  1068. var items = new List<JsValue>(arguments.Length + 1) {o};
  1069. items.AddRange(arguments);
  1070. uint n = 0;
  1071. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), 0);
  1072. var aOperations = ArrayOperations.For(a);
  1073. for (var i = 0; i < items.Count; i++)
  1074. {
  1075. var e = items[i];
  1076. if (e is ObjectInstance oi && oi.IsConcatSpreadable)
  1077. {
  1078. if (e is ArrayInstance eArray && a is ArrayInstance a2)
  1079. {
  1080. a2.CopyValues(eArray, 0, n, eArray.GetLength());
  1081. n += eArray.GetLength();
  1082. }
  1083. else
  1084. {
  1085. var operations = ArrayOperations.For(oi);
  1086. var len = operations.GetLongLength();
  1087. if (n + len > ArrayOperations.MaxArrayLikeLength)
  1088. {
  1089. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1090. }
  1091. for (uint k = 0; k < len; k++)
  1092. {
  1093. operations.TryGetValue(k, out var subElement);
  1094. aOperations.CreateDataPropertyOrThrow(n, subElement);
  1095. n++;
  1096. }
  1097. }
  1098. }
  1099. else
  1100. {
  1101. aOperations.CreateDataPropertyOrThrow(n, e);
  1102. n++;
  1103. }
  1104. }
  1105. // this is not in the specs, but is necessary in case the last element of the last
  1106. // array doesn't exist, and thus the length would not be incremented
  1107. a.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(n, PropertyFlag.OnlyWritable));
  1108. return a;
  1109. }
  1110. internal JsValue ToString(JsValue thisObj, JsValue[] arguments)
  1111. {
  1112. var array = TypeConverter.ToObject(_realm, thisObj);
  1113. Func<JsValue, JsValue[], JsValue> func;
  1114. if (array.Get("join") is ICallable joinFunc)
  1115. {
  1116. func = joinFunc.Call;
  1117. }
  1118. else
  1119. {
  1120. func = _realm.Intrinsics.Object.PrototypeObject.ToObjectString;
  1121. }
  1122. return func(array, Arguments.Empty);
  1123. }
  1124. /// <summary>
  1125. /// https://tc39.es/ecma262/#sec-array.prototype.reduceright
  1126. /// </summary>
  1127. private JsValue ReduceRight(JsValue thisObj, JsValue[] arguments)
  1128. {
  1129. var callbackfn = arguments.At(0);
  1130. var initialValue = arguments.At(1);
  1131. var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObj));
  1132. var len = o.GetLongLength();
  1133. var callable = GetCallable(callbackfn);
  1134. if (len == 0 && arguments.Length < 2)
  1135. {
  1136. ExceptionHelper.ThrowTypeError(_realm);
  1137. }
  1138. long k = (long) (len - 1);
  1139. JsValue accumulator = Undefined;
  1140. if (arguments.Length > 1)
  1141. {
  1142. accumulator = initialValue;
  1143. }
  1144. else
  1145. {
  1146. var kPresent = false;
  1147. while (kPresent == false && k >= 0)
  1148. {
  1149. if ((kPresent = o.TryGetValue((ulong) k, out var temp)))
  1150. {
  1151. accumulator = temp;
  1152. }
  1153. k--;
  1154. }
  1155. if (kPresent == false)
  1156. {
  1157. ExceptionHelper.ThrowTypeError(_realm);
  1158. }
  1159. }
  1160. var jsValues = new JsValue[4];
  1161. jsValues[3] = o.Target;
  1162. for (; k >= 0; k--)
  1163. {
  1164. if (o.TryGetValue((ulong) k, out var kvalue))
  1165. {
  1166. jsValues[0] = accumulator;
  1167. jsValues[1] = kvalue;
  1168. jsValues[2] = k;
  1169. accumulator = callable.Call(Undefined, jsValues);
  1170. }
  1171. }
  1172. return accumulator;
  1173. }
  1174. /// <summary>
  1175. /// https://tc39.es/ecma262/#sec-array.prototype.push
  1176. /// </summary>
  1177. public JsValue Push(JsValue thisObject, JsValue[] arguments)
  1178. {
  1179. if (thisObject is ArrayInstance arrayInstance)
  1180. {
  1181. return arrayInstance.Push(arguments);
  1182. }
  1183. var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObject));
  1184. var n = o.GetLongLength();
  1185. if (n + (ulong) arguments.Length > ArrayOperations.MaxArrayLikeLength)
  1186. {
  1187. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1188. }
  1189. foreach (var a in arguments)
  1190. {
  1191. o.Set(n, a, true);
  1192. n++;
  1193. }
  1194. o.SetLength(n);
  1195. return n;
  1196. }
  1197. public JsValue Pop(JsValue thisObject, JsValue[] arguments)
  1198. {
  1199. var o = ArrayOperations.For(_realm, thisObject);
  1200. ulong len = o.GetLongLength();
  1201. if (len == 0)
  1202. {
  1203. o.SetLength(0);
  1204. return Undefined;
  1205. }
  1206. len = len - 1;
  1207. JsValue element = o.Get(len);
  1208. o.DeletePropertyOrThrow(len);
  1209. o.SetLength(len);
  1210. return element;
  1211. }
  1212. private sealed class ArrayComparer : IComparer<JsValue>
  1213. {
  1214. /// <summary>
  1215. /// Default instance without any compare function.
  1216. /// </summary>
  1217. public static readonly ArrayComparer Default = new(null, null);
  1218. public static ArrayComparer WithFunction(Engine engine, ICallable compare)
  1219. {
  1220. if (compare == null)
  1221. {
  1222. return Default;
  1223. }
  1224. return new ArrayComparer(engine, compare);
  1225. }
  1226. private readonly Engine _engine;
  1227. private readonly ICallable _compare;
  1228. private readonly JsValue[] _comparableArray = new JsValue[2];
  1229. private ArrayComparer(Engine engine, ICallable compare)
  1230. {
  1231. _engine = engine;
  1232. _compare = compare;
  1233. }
  1234. public int Compare(JsValue x, JsValue y)
  1235. {
  1236. var xIsNull = ReferenceEquals(x, null);
  1237. var yIsNull = ReferenceEquals(y, null);
  1238. if (xIsNull)
  1239. {
  1240. if (yIsNull)
  1241. {
  1242. return 0;
  1243. }
  1244. return 1;
  1245. }
  1246. else
  1247. {
  1248. if (yIsNull)
  1249. {
  1250. return -1;
  1251. }
  1252. }
  1253. var xUndefined = x.IsUndefined();
  1254. var yUndefined = y.IsUndefined();
  1255. if (xUndefined && yUndefined)
  1256. {
  1257. return 0;
  1258. }
  1259. if (xUndefined)
  1260. {
  1261. return 1;
  1262. }
  1263. if (yUndefined)
  1264. {
  1265. return -1;
  1266. }
  1267. if (_compare != null)
  1268. {
  1269. _engine.RunBeforeExecuteStatementChecks(null);
  1270. _comparableArray[0] = x;
  1271. _comparableArray[1] = y;
  1272. var s = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1273. if (s < 0)
  1274. {
  1275. return -1;
  1276. }
  1277. if (s > 0)
  1278. {
  1279. return 1;
  1280. }
  1281. return 0;
  1282. }
  1283. var xString = TypeConverter.ToString(x);
  1284. var yString = TypeConverter.ToString(y);
  1285. return string.CompareOrdinal(xString, yString);
  1286. }
  1287. }
  1288. }
  1289. }