array_sparse_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package goja
  2. import "testing"
  3. func TestSparseArraySetLengthWithPropItems(t *testing.T) {
  4. const SCRIPT = `
  5. var a = [1,2,3,4];
  6. a[100000] = 5;
  7. var thrown = false;
  8. Object.defineProperty(a, "2", {value: 42, configurable: false, writable: false});
  9. try {
  10. Object.defineProperty(a, "length", {value: 0, writable: false});
  11. } catch (e) {
  12. thrown = e instanceof TypeError;
  13. }
  14. thrown && a.length === 3;
  15. `
  16. testScript1(SCRIPT, valueTrue, t)
  17. }
  18. func TestSparseArraySwitch(t *testing.T) {
  19. const SCRIPT = `
  20. var a = [];
  21. a[20470] = 5; // switch to sparse
  22. var cutoffIdx = Math.round(20470 - 20470/8);
  23. for (var i = a.length - 1; i >= cutoffIdx; i--) {
  24. a[i] = i;
  25. }
  26. // At this point it will have switched to a normal array
  27. if (a.length != 20471) {
  28. throw new Error("Invalid length: " + a.length);
  29. }
  30. for (var i = 0; i < cutoffIdx; i++) {
  31. if (a[i] !== undefined) {
  32. throw new Error("Invalid value at " + i + ": " + a[i]);
  33. }
  34. }
  35. for (var i = cutoffIdx; i < a.length; i++) {
  36. if (a[i] !== i) {
  37. throw new Error("Invalid value at " + i + ": " + a[i]);
  38. }
  39. }
  40. // Now try to expand. Should stay a normal array
  41. a[20471] = 20471;
  42. if (a.length != 20472) {
  43. throw new Error("Invalid length: " + a.length);
  44. }
  45. for (var i = 0; i < cutoffIdx; i++) {
  46. if (a[i] !== undefined) {
  47. throw new Error("Invalid value at " + i + ": " + a[i]);
  48. }
  49. }
  50. for (var i = cutoffIdx; i < a.length; i++) {
  51. if (a[i] !== i) {
  52. throw new Error("Invalid value at " + i + ": " + a[i]);
  53. }
  54. }
  55. // Delete enough elements for it to become sparse again.
  56. var cutoffIdx1 = Math.round(20472 - 20472/10);
  57. for (var i = cutoffIdx; i < cutoffIdx1; i++) {
  58. delete a[i];
  59. }
  60. // This should switch it back to sparse.
  61. a[25590] = 25590;
  62. if (a.length != 25591) {
  63. throw new Error("Invalid length: " + a.length);
  64. }
  65. for (var i = 0; i < cutoffIdx1; i++) {
  66. if (a[i] !== undefined) {
  67. throw new Error("Invalid value at " + i + ": " + a[i]);
  68. }
  69. }
  70. for (var i = cutoffIdx1; i < 20472; i++) {
  71. if (a[i] !== i) {
  72. throw new Error("Invalid value at " + i + ": " + a[i]);
  73. }
  74. }
  75. for (var i = 20472; i < 25590; i++) {
  76. if (a[i] !== undefined) {
  77. throw new Error("Invalid value at " + i + ": " + a[i]);
  78. }
  79. }
  80. if (a[25590] !== 25590) {
  81. throw new Error("Invalid value at 25590: " + a[25590]);
  82. }
  83. `
  84. testScript1(SCRIPT, _undefined, t)
  85. }