Praktikum_mf

Реализация массива

Mar 30th, 2021
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class MyArray {
  2.     constructor(initialSize = 1) {
  3.         if (Number(initialSize) !== initialSize || Math.round(initialSize) !== initialSize) {
  4.             throw new Error('Длина массива должна быть целым числом');
  5.         }
  6.         if (!(initialSize > 0)) {
  7.         throw new Error('Размер массива должен быть больше нуля');
  8.     }
  9.  
  10.         this.size = initialSize;
  11.         this.memory = allocate(initialSize);
  12.         this.length = 0;
  13.     }
  14.  
  15.     get(index){
  16.         this._checkIndex(index);
  17.         return this.memory[index];
  18.     }
  19.  
  20.     set(index, value) {
  21.         this._checkIndex(index);
  22.         this.memory[index] = value;
  23.     }
  24.  
  25.     add(value, index) {
  26.         if (index === undefined) {
  27.             this.memory[this.length] = value;
  28.         } else {
  29.             this._checkIndex(index);
  30.  
  31.             for (let i = this.length; i > index; i--) {
  32.                 this.memory[i] = this.memory[i - 1];
  33.             }
  34.  
  35.             this.memory[index] = value;
  36.         }
  37.  
  38.         this.length++;
  39.  
  40.         if (this.length === this.size) {
  41.         this._resize();
  42.     }
  43.  
  44.         return this.length;
  45.     }
  46.  
  47.     delete(index) {
  48.         this._checkIndex(index);
  49.  
  50.         for (let i = index + 1; i < this.length; i++) {
  51.             this.memory[i - 1] = this.memory[i];
  52.         }
  53.  
  54.         this.length--;
  55.         this.memory[this.length] = undefined;
  56.  
  57.         return this.length;
  58.     }
  59.  
  60.     _resize() {
  61.     const newSize = this.size * 2;
  62.         const newMemory = allocate(newSize);
  63.  
  64.         for (let i = 0; i < this.size; i++) {
  65.             newMemory[i] = this.memory[i];
  66.         }
  67.  
  68.     this.size = newSize;
  69.         this.memory = newMemory;
  70.     }
  71.  
  72.     _checkIndex(index) {
  73.         if (index < 0 || index >= this.length) {
  74.             throw new Error('Индекс за пределами массива');
  75.         }
  76.     }
  77. }
  78.  
  79. function allocate(size) {
  80.     const memory = {};
  81.  
  82.     for (let i = 0; i < size; i++) {
  83.         memory[i] = undefined;
  84.     }
  85.  
  86.     return memory;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment