우선 순위 Queue

YANG쓰·2022년 5월 19일
0

JS

목록 보기
2/5
// data 우선 순위를 저장하기 위한 생성자 함수
function Element(data, priority){
    this.data = data;
    this.priority = priority;
}

//Element 관리를 위한 생성자
function Priorityqueue(){
    this.array = [];
    
}
//객체 내 데이터 셋 반환
Priorityqueue.prototype.getBuffer = function(){
return this.array.map((element) => element.data)
}


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

//데이터와 우선 순위를 받고 새로운 엘레먼트를 만듬
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){
            // 새로 들어온 엘레먼트보다 낮은 인덱스일 경우
        // 기존 1,1,2,3일때 앞쪽부터 계속 탐색하고,i번째 인덱스에 변경삭제 없이 엘레먼트를 하나 추가해준다.
            this.array.splice(i,0,element);
            // 그렇게 되면 엘레먼트가 하나 들어오게 되면서 added는 True.
            added = true;
            // 그리고 멈춘다.
            break;// for문 탈출
        }
    }
    // 추가가 되지 않는다면 Push를 통해서 기존 엘레먼트를 추가한다.
    if(!added){
        this.array.push(element);
    }

    return this.array.length;
}


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




let pq = new Priorityqueue();

pq.enqueue("Alice",1);
pq.enqueue("Bob",2);

console.log(pq);
//Priorityqueue {
  array: [
    Element { data: 'Alice', priority: 1 },
    Element { data: 'Bob', priority: 2 }
  ]
}

pq.enqueue("Tom",1);
pq.enqueue("john",3);


console.log(pq);

//
Priorityqueue {
  array: [
    Element { data: 'Alice', priority: 1 },
    Element { data: 'Tom', priority: 1 },
    Element { data: 'Bob', priority: 2 },
    Element { data: 'john', priority: 3 }
  ]
}

우선 순위를 기반으로 한 queue이다.

우선순위 기반이므로 늦게 들어와도 우선순위를 지정한것이 더 앞서있을 경우는 기존에 있더라도 뒤로 밀리게 된다.

profile
양쓰

0개의 댓글