Array.prototype-generic-functions.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. load("test-common.js");
  2. try {
  3. [undefined, "foo", -42, 0].forEach(length => {
  4. const o = { length };
  5. assert(Array.prototype.push.call(o, "foo") === 1);
  6. assert(o.length === 1);
  7. assert(o[0] === "foo");
  8. assert(Array.prototype.push.call(o, "bar", "baz") === 3);
  9. assert(o.length === 3);
  10. assert(o[0] === "foo");
  11. assert(o[1] === "bar");
  12. assert(o[2] === "baz");
  13. assert(Array.prototype.pop.call(o) === "baz");
  14. assert(o.length === 2);
  15. assert(Array.prototype.pop.call(o) === "bar");
  16. assert(o.length === 1);
  17. assert(Array.prototype.pop.call(o) === "foo");
  18. assert(o.length === 0);
  19. assert(Array.prototype.pop.call(o) === undefined);
  20. assert(o.length === 0);
  21. o.length = length;
  22. assert(Array.prototype.pop.call(o) === undefined);
  23. assert(o.length === 0);
  24. });
  25. const o = { length: 5, 0: "foo", 1: "bar", 3: "baz" };
  26. {
  27. const visited = [];
  28. Array.prototype.every.call(o, function (value) {
  29. visited.push(value);
  30. return true;
  31. });
  32. assert(visited.length === 3);
  33. assert(visited[0] === "foo");
  34. assert(visited[1] === "bar");
  35. assert(visited[2] === "baz");
  36. }
  37. ["find", "findIndex"].forEach(name => {
  38. const visited = [];
  39. Array.prototype[name].call(o, function (value) {
  40. visited.push(value);
  41. return false;
  42. });
  43. assert(visited.length === 5);
  44. assert(visited[0] === "foo");
  45. assert(visited[1] === "bar");
  46. assert(visited[2] === undefined);
  47. assert(visited[3] === "baz");
  48. assert(visited[4] === undefined);
  49. });
  50. ["filter", "forEach", "map", "some"].forEach(name => {
  51. const visited = [];
  52. Array.prototype[name].call(o, function (value) {
  53. visited.push(value);
  54. return false;
  55. });
  56. assert(visited.length === 3);
  57. assert(visited[0] === "foo");
  58. assert(visited[1] === "bar");
  59. assert(visited[2] === "baz");
  60. });
  61. console.log("PASS");
  62. } catch (e) {
  63. console.log("FAIL: " + e);
  64. }