ArrayPrototype.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * Copyright (c) 2020, Marcin Gasperowicz <xnooga@gmail.com>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice, this
  11. * list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright notice,
  14. * this list of conditions and the following disclaimer in the documentation
  15. * and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  23. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  24. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  25. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include <AK/Function.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibJS/Heap/Heap.h>
  31. #include <LibJS/Interpreter.h>
  32. #include <LibJS/Runtime/Array.h>
  33. #include <LibJS/Runtime/ArrayPrototype.h>
  34. #include <LibJS/Runtime/Error.h>
  35. #include <LibJS/Runtime/Function.h>
  36. #include <LibJS/Runtime/GlobalObject.h>
  37. #include <LibJS/Runtime/MarkedValueList.h>
  38. #include <LibJS/Runtime/ObjectPrototype.h>
  39. #include <LibJS/Runtime/Value.h>
  40. namespace JS {
  41. ArrayPrototype::ArrayPrototype()
  42. : Object(interpreter().global_object().object_prototype())
  43. {
  44. u8 attr = Attribute::Writable | Attribute::Configurable;
  45. put_native_function("filter", filter, 1, attr);
  46. put_native_function("forEach", for_each, 1, attr);
  47. put_native_function("map", map, 1, attr);
  48. put_native_function("pop", pop, 0, attr);
  49. put_native_function("push", push, 1, attr);
  50. put_native_function("shift", shift, 0, attr);
  51. put_native_function("toString", to_string, 0, attr);
  52. put_native_function("unshift", unshift, 1, attr);
  53. put_native_function("join", join, 1, attr);
  54. put_native_function("concat", concat, 1, attr);
  55. put_native_function("slice", slice, 2, attr);
  56. put_native_function("indexOf", index_of, 1, attr);
  57. put_native_function("reduce", reduce, 1, attr);
  58. put_native_function("reduceRight", reduce_right, 1, attr);
  59. put_native_function("reverse", reverse, 0, attr);
  60. put_native_function("lastIndexOf", last_index_of, 1, attr);
  61. put_native_function("includes", includes, 1, attr);
  62. put_native_function("find", find, 1, attr);
  63. put_native_function("findIndex", find_index, 1, attr);
  64. put_native_function("some", some, 1, attr);
  65. put_native_function("every", every, 1, attr);
  66. put("length", Value(0), Attribute::Configurable);
  67. }
  68. ArrayPrototype::~ArrayPrototype()
  69. {
  70. }
  71. static Function* callback_from_args(Interpreter& interpreter, const String& name)
  72. {
  73. if (interpreter.argument_count() < 1) {
  74. interpreter.throw_exception<TypeError>(String::format("Array.prototype.%s() requires at least one argument", name.characters()));
  75. return nullptr;
  76. }
  77. auto callback = interpreter.argument(0);
  78. if (!callback.is_function()) {
  79. interpreter.throw_exception<TypeError>(String::format("%s is not a function", callback.to_string_without_side_effects().characters()));
  80. return nullptr;
  81. }
  82. return &callback.as_function();
  83. }
  84. static size_t get_length(Interpreter& interpreter, Object& object)
  85. {
  86. auto length_property = object.get("length");
  87. if (interpreter.exception())
  88. return 0;
  89. return length_property.to_size_t(interpreter);
  90. }
  91. static void for_each_item(Interpreter& interpreter, const String& name, AK::Function<IterationDecision(size_t index, Value value, Value callback_result)> callback, bool skip_empty = true)
  92. {
  93. auto* this_object = interpreter.this_value().to_object(interpreter);
  94. if (!this_object)
  95. return;
  96. auto initial_length = get_length(interpreter, *this_object);
  97. if (interpreter.exception())
  98. return;
  99. auto* callback_function = callback_from_args(interpreter, name);
  100. if (!callback_function)
  101. return;
  102. auto this_value = interpreter.argument(1);
  103. for (size_t i = 0; i < initial_length; ++i) {
  104. auto value = this_object->get_by_index(i);
  105. if (interpreter.exception())
  106. return;
  107. if (value.is_empty()) {
  108. if (skip_empty)
  109. continue;
  110. value = js_undefined();
  111. }
  112. MarkedValueList arguments(interpreter.heap());
  113. arguments.append(value);
  114. arguments.append(Value((i32)i));
  115. arguments.append(this_object);
  116. auto callback_result = interpreter.call(*callback_function, this_value, move(arguments));
  117. if (interpreter.exception())
  118. return;
  119. if (callback(i, value, callback_result) == IterationDecision::Break)
  120. break;
  121. }
  122. }
  123. Value ArrayPrototype::filter(Interpreter& interpreter)
  124. {
  125. auto* new_array = Array::create(interpreter.global_object());
  126. for_each_item(interpreter, "filter", [&](auto, auto value, auto callback_result) {
  127. if (callback_result.to_boolean())
  128. new_array->elements().append(value);
  129. return IterationDecision::Continue;
  130. });
  131. return Value(new_array);
  132. }
  133. Value ArrayPrototype::for_each(Interpreter& interpreter)
  134. {
  135. for_each_item(interpreter, "forEach", [](auto, auto, auto) {
  136. return IterationDecision::Continue;
  137. });
  138. return js_undefined();
  139. }
  140. Value ArrayPrototype::map(Interpreter& interpreter)
  141. {
  142. auto* this_object = interpreter.this_value().to_object(interpreter);
  143. if (!this_object)
  144. return {};
  145. auto initial_length = get_length(interpreter, *this_object);
  146. if (interpreter.exception())
  147. return {};
  148. auto* new_array = Array::create(interpreter.global_object());
  149. new_array->elements().resize(initial_length);
  150. for_each_item(interpreter, "map", [&](auto index, auto, auto callback_result) {
  151. new_array->elements()[index] = callback_result;
  152. return IterationDecision::Continue;
  153. });
  154. return Value(new_array);
  155. }
  156. Value ArrayPrototype::push(Interpreter& interpreter)
  157. {
  158. auto* this_object = interpreter.this_value().to_object(interpreter);
  159. if (!this_object)
  160. return {};
  161. if (this_object->is_array()) {
  162. auto* array = static_cast<Array*>(this_object);
  163. for (size_t i = 0; i < interpreter.argument_count(); ++i)
  164. array->elements().append(interpreter.argument(i));
  165. return Value(array->length());
  166. }
  167. auto length = get_length(interpreter, *this_object);
  168. if (interpreter.exception())
  169. return {};
  170. auto argument_count = interpreter.argument_count();
  171. auto new_length = length + argument_count;
  172. if (new_length > MAX_ARRAY_LIKE_INDEX)
  173. return interpreter.throw_exception<TypeError>("Maximum array size exceeded");
  174. for (size_t i = 0; i < argument_count; ++i)
  175. this_object->put_by_index(length + i, interpreter.argument(i));
  176. auto new_length_value = Value((i32)new_length);
  177. this_object->put("length", new_length_value);
  178. if (interpreter.exception())
  179. return {};
  180. return new_length_value;
  181. }
  182. Value ArrayPrototype::unshift(Interpreter& interpreter)
  183. {
  184. auto* array = array_from(interpreter);
  185. if (!array)
  186. return {};
  187. for (size_t i = 0; i < interpreter.argument_count(); ++i)
  188. array->elements().insert(i, interpreter.argument(i));
  189. return Value(array->length());
  190. }
  191. Value ArrayPrototype::pop(Interpreter& interpreter)
  192. {
  193. auto* this_object = interpreter.this_value().to_object(interpreter);
  194. if (!this_object)
  195. return {};
  196. if (this_object->is_array()) {
  197. auto* array = static_cast<Array*>(this_object);
  198. if (array->elements().is_empty())
  199. return js_undefined();
  200. return array->elements().take_last().value_or(js_undefined());
  201. }
  202. auto length = get_length(interpreter, *this_object);
  203. if (length == 0) {
  204. this_object->put("length", Value(0));
  205. return js_undefined();
  206. }
  207. auto index = length - 1;
  208. auto element = this_object->get_by_index(index).value_or(js_undefined());
  209. if (interpreter.exception())
  210. return {};
  211. this_object->delete_property(PropertyName(index));
  212. this_object->put("length", Value((i32)index));
  213. if (interpreter.exception())
  214. return {};
  215. return element;
  216. }
  217. Value ArrayPrototype::shift(Interpreter& interpreter)
  218. {
  219. auto* array = array_from(interpreter);
  220. if (!array)
  221. return {};
  222. if (array->elements().is_empty())
  223. return js_undefined();
  224. return array->elements().take_first().value_or(js_undefined());
  225. }
  226. Value ArrayPrototype::to_string(Interpreter& interpreter)
  227. {
  228. auto* this_object = interpreter.this_value().to_object(interpreter);
  229. if (!this_object)
  230. return {};
  231. auto join_function = this_object->get("join");
  232. if (interpreter.exception())
  233. return {};
  234. if (!join_function.is_function())
  235. return ObjectPrototype::to_string(interpreter);
  236. return interpreter.call(join_function.as_function(), this_object);
  237. }
  238. Value ArrayPrototype::join(Interpreter& interpreter)
  239. {
  240. auto* this_object = interpreter.this_value().to_object(interpreter);
  241. if (!this_object)
  242. return {};
  243. String separator = ",";
  244. if (interpreter.argument_count()) {
  245. separator = interpreter.argument(0).to_string(interpreter);
  246. if (interpreter.exception())
  247. return {};
  248. }
  249. auto length = get_length(interpreter, *this_object);
  250. if (interpreter.exception())
  251. return {};
  252. StringBuilder builder;
  253. for (size_t i = 0; i < length; ++i) {
  254. if (i > 0)
  255. builder.append(separator);
  256. auto value = this_object->get_by_index(i).value_or(js_undefined());
  257. if (interpreter.exception())
  258. return {};
  259. if (value.is_undefined() || value.is_null())
  260. continue;
  261. auto string = value.to_string(interpreter);
  262. if (interpreter.exception())
  263. return {};
  264. builder.append(string);
  265. }
  266. return js_string(interpreter, builder.to_string());
  267. }
  268. Value ArrayPrototype::concat(Interpreter& interpreter)
  269. {
  270. auto* array = array_from(interpreter);
  271. if (!array)
  272. return {};
  273. auto* new_array = Array::create(interpreter.global_object());
  274. new_array->elements().append(array->elements());
  275. for (size_t i = 0; i < interpreter.argument_count(); ++i) {
  276. auto argument = interpreter.argument(i);
  277. if (argument.is_array()) {
  278. auto& argument_object = argument.as_object();
  279. new_array->elements().append(argument_object.elements());
  280. } else {
  281. new_array->elements().append(argument);
  282. }
  283. }
  284. return Value(new_array);
  285. }
  286. Value ArrayPrototype::slice(Interpreter& interpreter)
  287. {
  288. auto* array = array_from(interpreter);
  289. if (!array)
  290. return {};
  291. auto* new_array = Array::create(interpreter.global_object());
  292. if (interpreter.argument_count() == 0) {
  293. new_array->elements().append(array->elements());
  294. return new_array;
  295. }
  296. ssize_t array_size = static_cast<ssize_t>(array->elements().size());
  297. auto start_slice = interpreter.argument(0).to_i32(interpreter);
  298. if (interpreter.exception())
  299. return {};
  300. auto end_slice = array_size;
  301. if (start_slice > array_size)
  302. return new_array;
  303. if (start_slice < 0)
  304. start_slice = end_slice + start_slice;
  305. if (interpreter.argument_count() >= 2) {
  306. end_slice = interpreter.argument(1).to_i32(interpreter);
  307. if (interpreter.exception())
  308. return {};
  309. if (end_slice < 0)
  310. end_slice = array_size + end_slice;
  311. else if (end_slice > array_size)
  312. end_slice = array_size;
  313. }
  314. size_t array_capacity = start_slice + array_size - end_slice;
  315. new_array->elements().ensure_capacity(array_capacity);
  316. for (ssize_t i = start_slice; i < end_slice; ++i) {
  317. new_array->elements().append(array->elements().at(i));
  318. }
  319. return new_array;
  320. }
  321. Value ArrayPrototype::index_of(Interpreter& interpreter)
  322. {
  323. auto* array = array_from(interpreter);
  324. if (!array)
  325. return {};
  326. i32 array_size = static_cast<i32>(array->elements().size());
  327. if (array_size == 0)
  328. return Value(-1);
  329. i32 from_index = 0;
  330. if (interpreter.argument_count() >= 2) {
  331. from_index = interpreter.argument(1).to_i32(interpreter);
  332. if (interpreter.exception())
  333. return {};
  334. if (from_index >= array_size)
  335. return Value(-1);
  336. auto negative_min_index = ((array_size - 1) * -1);
  337. if (from_index < negative_min_index)
  338. from_index = 0;
  339. else if (from_index < 0)
  340. from_index = array_size + from_index;
  341. }
  342. auto search_element = interpreter.argument(0);
  343. for (i32 i = from_index; i < array_size; ++i) {
  344. auto& element = array->elements().at(i);
  345. if (strict_eq(interpreter, element, search_element))
  346. return Value(i);
  347. }
  348. return Value(-1);
  349. }
  350. Value ArrayPrototype::reduce(Interpreter& interpreter)
  351. {
  352. auto* this_object = interpreter.this_value().to_object(interpreter);
  353. if (!this_object)
  354. return {};
  355. auto initial_length = get_length(interpreter, *this_object);
  356. if (interpreter.exception())
  357. return {};
  358. auto* callback_function = callback_from_args(interpreter, "reduce");
  359. if (!callback_function)
  360. return {};
  361. size_t start = 0;
  362. auto accumulator = js_undefined();
  363. if (interpreter.argument_count() > 1) {
  364. accumulator = interpreter.argument(1);
  365. } else {
  366. bool start_found = false;
  367. while (!start_found && start < initial_length) {
  368. auto value = this_object->get_by_index(start);
  369. if (interpreter.exception())
  370. return {};
  371. start_found = !value.is_empty();
  372. if (start_found)
  373. accumulator = value;
  374. start += 1;
  375. }
  376. if (!start_found) {
  377. interpreter.throw_exception<TypeError>("Reduce of empty array with no initial value");
  378. return {};
  379. }
  380. }
  381. auto this_value = js_undefined();
  382. for (size_t i = start; i < initial_length; ++i) {
  383. auto value = this_object->get_by_index(i);
  384. if (interpreter.exception())
  385. return {};
  386. if (value.is_empty())
  387. continue;
  388. MarkedValueList arguments(interpreter.heap());
  389. arguments.append(accumulator);
  390. arguments.append(value);
  391. arguments.append(Value((i32)i));
  392. arguments.append(this_object);
  393. accumulator = interpreter.call(*callback_function, this_value, move(arguments));
  394. if (interpreter.exception())
  395. return {};
  396. }
  397. return accumulator;
  398. }
  399. Value ArrayPrototype::reduce_right(Interpreter& interpreter)
  400. {
  401. auto* this_object = interpreter.this_value().to_object(interpreter);
  402. if (!this_object)
  403. return {};
  404. auto initial_length = get_length(interpreter, *this_object);
  405. if (interpreter.exception())
  406. return {};
  407. auto* callback_function = callback_from_args(interpreter, "reduceRight");
  408. if (!callback_function)
  409. return {};
  410. int start = initial_length - 1;
  411. auto accumulator = js_undefined();
  412. if (interpreter.argument_count() > 1) {
  413. accumulator = interpreter.argument(1);
  414. } else {
  415. bool start_found = false;
  416. while (!start_found && start >= 0) {
  417. auto value = this_object->get_by_index(start);
  418. if (interpreter.exception())
  419. return {};
  420. start_found = !value.is_empty();
  421. if (start_found)
  422. accumulator = value;
  423. start -= 1;
  424. }
  425. if (!start_found) {
  426. interpreter.throw_exception<TypeError>("Reduce of empty array with no initial value");
  427. return {};
  428. }
  429. }
  430. auto this_value = js_undefined();
  431. for (int i = start; i >= 0; --i) {
  432. auto value = this_object->get_by_index(i);
  433. if (interpreter.exception())
  434. return {};
  435. if (value.is_empty())
  436. continue;
  437. MarkedValueList arguments(interpreter.heap());
  438. arguments.append(accumulator);
  439. arguments.append(value);
  440. arguments.append(Value(i));
  441. arguments.append(this_object);
  442. accumulator = interpreter.call(*callback_function, this_value, move(arguments));
  443. if (interpreter.exception())
  444. return {};
  445. }
  446. return accumulator;
  447. }
  448. Value ArrayPrototype::reverse(Interpreter& interpreter)
  449. {
  450. auto* array = array_from(interpreter);
  451. if (!array)
  452. return {};
  453. if (array->elements().size() == 0)
  454. return array;
  455. Vector<Value> array_reverse;
  456. array_reverse.ensure_capacity(array->elements().size());
  457. for (ssize_t i = array->elements().size() - 1; i >= 0; --i)
  458. array_reverse.append(array->elements().at(i));
  459. array->elements() = move(array_reverse);
  460. return array;
  461. }
  462. Value ArrayPrototype::last_index_of(Interpreter& interpreter)
  463. {
  464. auto* array = array_from(interpreter);
  465. if (!array)
  466. return {};
  467. i32 array_size = static_cast<i32>(array->elements().size());
  468. if (array_size == 0)
  469. return Value(-1);
  470. i32 from_index = array_size - 1;
  471. if (interpreter.argument_count() >= 2) {
  472. from_index = interpreter.argument(1).to_i32(interpreter);
  473. if (interpreter.exception())
  474. return {};
  475. if (from_index >= 0)
  476. from_index = min(from_index, array_size - 1);
  477. else
  478. from_index = array_size + from_index;
  479. }
  480. auto search_element = interpreter.argument(0);
  481. for (i32 i = from_index; i >= 0; --i) {
  482. auto& element = array->elements().at(i);
  483. if (strict_eq(interpreter, element, search_element))
  484. return Value(i);
  485. }
  486. return Value(-1);
  487. }
  488. Value ArrayPrototype::includes(Interpreter& interpreter)
  489. {
  490. auto* array = array_from(interpreter);
  491. if (!array)
  492. return {};
  493. i32 array_size = array->elements().size();
  494. if (array_size == 0)
  495. return Value(false);
  496. i32 from_index = 0;
  497. if (interpreter.argument_count() >= 2) {
  498. from_index = interpreter.argument(1).to_i32(interpreter);
  499. if (interpreter.exception())
  500. return {};
  501. if (from_index >= array_size)
  502. return Value(false);
  503. auto negative_min_index = ((array_size - 1) * -1);
  504. if (from_index < negative_min_index)
  505. from_index = 0;
  506. else if (from_index < 0)
  507. from_index = array_size + from_index;
  508. }
  509. auto value_to_find = interpreter.argument(0);
  510. for (i32 i = from_index; i < array_size; ++i) {
  511. auto& element = array->elements().at(i);
  512. if (same_value_zero(interpreter, element, value_to_find))
  513. return Value(true);
  514. }
  515. return Value(false);
  516. }
  517. Value ArrayPrototype::find(Interpreter& interpreter)
  518. {
  519. auto result = js_undefined();
  520. for_each_item(
  521. interpreter, "find", [&](auto, auto value, auto callback_result) {
  522. if (callback_result.to_boolean()) {
  523. result = value;
  524. return IterationDecision::Break;
  525. }
  526. return IterationDecision::Continue;
  527. },
  528. false);
  529. return result;
  530. }
  531. Value ArrayPrototype::find_index(Interpreter& interpreter)
  532. {
  533. auto result_index = -1;
  534. for_each_item(
  535. interpreter, "findIndex", [&](auto index, auto, auto callback_result) {
  536. if (callback_result.to_boolean()) {
  537. result_index = index;
  538. return IterationDecision::Break;
  539. }
  540. return IterationDecision::Continue;
  541. },
  542. false);
  543. return Value(result_index);
  544. }
  545. Value ArrayPrototype::some(Interpreter& interpreter)
  546. {
  547. auto result = false;
  548. for_each_item(interpreter, "some", [&](auto, auto, auto callback_result) {
  549. if (callback_result.to_boolean()) {
  550. result = true;
  551. return IterationDecision::Break;
  552. }
  553. return IterationDecision::Continue;
  554. });
  555. return Value(result);
  556. }
  557. Value ArrayPrototype::every(Interpreter& interpreter)
  558. {
  559. auto result = true;
  560. for_each_item(interpreter, "every", [&](auto, auto, auto callback_result) {
  561. if (!callback_result.to_boolean()) {
  562. result = false;
  563. return IterationDecision::Break;
  564. }
  565. return IterationDecision::Continue;
  566. });
  567. return Value(result);
  568. }
  569. }