❶ 우선순위 큐

❓ 먼저 들어오는 데이터가 먼저 나가는 FIFO 형식의 자료 구조 (자판기를 생각하면 됨)

💡 FIFO 예시

❷ 우선 순위 구현 하기

(1) Element() : 데이터와 우선 순위를 저장하기 위한 생성자 함수

function Element(data, priority) {
  this.data = data;
  this.priority = priority;
}

(2) priorityQueue() : Element를 관리하기 위한 생성자 함수

function PriorityQueue() {
  this.array = [];
}

(3) getBuffer() : 객체 내 데이터 셋 반환

PriorityQueue.prototype.getBuffer = function () {
  return this.array.map((element) => element.data);
}

(4) isEmpty() : 객체 내 데이터 존재 여부 파악

PriorityQueue.prototype.isEmpty = function () {
  return this.array.length === 0;
}

(5) enqueue() : 데이터 추가

데이터 삭제 없이 추가가 될 수 있게 구현했기 때문에 코드가 push보다 길다.

PriorityQueue.prototype.enqueue = function (data, priority) {
  let element = new Element(data, priority);
  let added = false;

  for (let i = 0; i < this.array.length; i++) {
    if (element.priority < this.array[i].priority) {
      this.array.splice(i, 0, element);
      added = true;
      break;
    }
  }

  if (!added) {
    this.array.push(element);
  }

  return this.array.length;
}

(6) dequeue() : 데이터 삭제

PriorityQueue.prototype.dequeue = function () {
  return this.array.shift();
}

(7) front() : 가장 첫 데이터 반환

PriorityQueue.prototype.front = function () {
  return this.array.length == 0 ? undefined : this.array[0].data;
}

(8) size() : 큐 내 데이터 개수 확인

PriorityQueue.prototype.size = function () {
  return this.array.length;
}

(9) clear() : 큐 초기화 (전체 삭제)

PriorityQueue.prototype.clear = function () {
  this.array = [];
}
profile
#UXUI #코린이

0개의 댓글