List

List 구현하기

class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }
  // search
  // O(1)
  get(index) {
    return this.data[index];
  }
  // O(1)
  push(item) {
    this.data[this.length] = item;
    this.length++;
    return this.data;
  }
  // O(1)
  pop() {
    const lastItem = this.data[this.length - 1];
    delete this.data[this.length - 1];
    this.length--;
    return lastItem;
  }
  // 원하는 index 의 요소 제거
  // O(N) - 최악 시나리오 (첫번째 요소 제거)
  deleteAtIndex(index) {
    const item = this.data[index];
    shiftItems(index);
    return item;

    function shiftItems(index) {
      for (let i = index; i < this.length - 1; i++) {
        this.data[i] = this.data[i + 1];
      }
      delete this.data[this.length - 1];
      this.length--;
    }
  }
}

const myArray = new MyArray();
myArray.push("hi");
myArray.push("you");
myArray.push("!");
myArray.pop();
myArray.deleteAtIndex(0);
myArray.push("are");
myArray.push("nice");
myArray.shiftItems(0);
console.log(myArray);