ArrayPrototype.cpp 16 KB

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