push4_traps.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. var arr = [], arr2 = [];
  7. let setCount = 0;
  8. let getCount = 0;
  9. function check(actual, expected)
  10. {
  11. if (actual !== expected)
  12. {
  13. throw new Error("Wrong value actual: " + actual + " expected: " + expected);
  14. }
  15. }
  16. // Test push traps with int based accessors on prototype
  17. Object.defineProperty(Array.prototype, '0', {
  18. get: function() {
  19. ++getCount;
  20. return 30;
  21. },
  22. set: function() {
  23. ++setCount;
  24. return 60;
  25. },
  26. configurable: true
  27. });
  28. arr.push(1);
  29. check(arr.length, 1);
  30. check(setCount, 1);
  31. check(getCount, 0);
  32. check(JSON.stringify(arr), '[30]')
  33. check(setCount, 1);
  34. check(getCount, 1);
  35. check(arr[0], 30);
  36. check(getCount, 2);
  37. check(arr2[0], 30);
  38. check(arr2.length, 0);
  39. // Test push traps with float based accessors on prototype
  40. Object.defineProperty(Array.prototype, '0', {
  41. get: function() {
  42. ++getCount;
  43. return 30.5;
  44. },
  45. set: function() {
  46. ++setCount;
  47. return 60.3;
  48. },
  49. configurable: true
  50. });
  51. arr.push(1);
  52. arr2.push(0.5);
  53. check(arr.length, 2);
  54. check(arr2.length, 1);
  55. check(setCount, 2);
  56. check(getCount, 3);
  57. check(JSON.stringify(arr), '[30.5,1]');
  58. check(JSON.stringify(arr2), '[30.5]');
  59. check(setCount, 2);
  60. check(getCount, 5);
  61. check(arr[0], 30.5);
  62. check(arr[1], 1);
  63. check(arr2[0], 30.5);
  64. check(getCount, 7);
  65. print("pass");