태그 : queue shift javascript

Queue

자바스크립트는 큐나 스택의 자료구조가 따로 없다.

따라서 Queue를 구현하여 사용할 수 있는데 이때 만약 shift()를 사용하면 대상개체가 많으면 많을 수록 굉장히 비효율적인 현상이 발생한다.

size와 empty함수를 제외하고 Queue를 구현하면 다음과 같다.

shift()를 사용한 Queue구현

class Queue {
  constructor() {
    this.store = []
  }
  enqueue (item) {
    this.store.push(item)
  }
  dequeue () {
    this.store.shift()
  }
}

shift() 함수는 배열의 가장 첫번째 아이템을 제거하는데 이때 앞에 아이템이 제거됨으로써 배열의 인덱스가 전부 변경된다. 따라서 배열이 크면 클수록 엄청난 비용이 소모될 수 있다.

shift()를 사용하지 않은 Queue구현

class Queue {
  constructor() {
    this.store = {}
    this.head = 0
    this.tail = 0
  }
  enqueue (item) {
    this.store[this.tail] = item
    this.tail++
  }
  dequeue () {
    delete this.store[this.head]
    this.head++
    if (this.tail - this.head === 0) {
      this.head = 0
      this.tail = 0
    }
    if (this.tail - this.head <= 0) return undefined
  }
}

따라서 shift()로 인한 시간비용을 줄이기 위해서는 위와 같이 형식의 Queue를 구현하는것이 더 좋다.

◀️ 욕심쟁이(Greedy)... 다이나믹 프로그래밍 ▶️
comments powered by Disqus