You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.5 KiB

4 years ago
  1. const SUBARRAY_SIZE = 0x10000;
  2. const BigArrayHandler = {
  3. get: function(obj, prop) {
  4. if (!isNaN(prop)) {
  5. return obj.getElement(prop);
  6. } else return obj[prop];
  7. },
  8. set: function(obj, prop, value) {
  9. if (!isNaN(prop)) {
  10. return obj.setElement(prop, value);
  11. } else {
  12. obj[prop] = value;
  13. return true;
  14. }
  15. }
  16. };
  17. class _BigArray {
  18. constructor (initSize) {
  19. this.length = initSize || 0;
  20. this.arr = [];
  21. for (let i=0; i<initSize; i+=SUBARRAY_SIZE) {
  22. this.arr[i/SUBARRAY_SIZE] = new Array(Math.min(SUBARRAY_SIZE, initSize - i));
  23. }
  24. return this;
  25. }
  26. push (element) {
  27. this.setElement (this.length, element);
  28. }
  29. getElement(idx) {
  30. idx = parseInt(idx);
  31. const idx1 = Math.floor(idx / SUBARRAY_SIZE);
  32. const idx2 = idx % SUBARRAY_SIZE;
  33. return this.arr[idx1] ? this.arr[idx1][idx2] : undefined;
  34. }
  35. setElement(idx, value) {
  36. idx = parseInt(idx);
  37. const idx1 = Math.floor(idx / SUBARRAY_SIZE);
  38. if (!this.arr[idx1]) {
  39. this.arr[idx1] = [];
  40. }
  41. const idx2 = idx % SUBARRAY_SIZE;
  42. this.arr[idx1][idx2] = value;
  43. if (idx >= this.length) this.length = idx+1;
  44. return true;
  45. }
  46. }
  47. class BigArray {
  48. constructor( initSize ) {
  49. const obj = new _BigArray(initSize);
  50. const extObj = new Proxy(obj, BigArrayHandler);
  51. return extObj;
  52. }
  53. }
  54. module.exports = BigArray;