js模拟队列----小优先队列
2018-06-19 10:56 muamaker 阅读(472) 评论(0) 编辑 收藏 举报队列:先进先出,后进后出
var Queue = (function(){ var item = new WeakMap(); class Queue{ constructor(){ item.set(this,[]); } enqueue(ele,priority){ var ls = item.get(this); var obj = { ele:ele, pro:priority }; var add = false; for(var i = 0; i < ls.length; i++ ){ if(priority < ls[i].pro){ ls.splice(i,0,obj); add = true; break; } } if(!add){ ls.push(obj); } } dequeue(){ var ls = item.get(this); return ls.shift(); } size(){ var ls = item.get(this); return ls.length; } front(){ var ls = item.get(this); return ls[0]; } isEmpty(){ var ls = item.get(this); return !ls.length; } print(){ var ls = item.get(this); for(var i = 0; i < ls.length; i++){ console.log(`${ls[i].ele}-${ls[i].pro}`); } } } return Queue; })(); var queue = new Queue(); queue.enqueue("b",2); queue.enqueue("a",1); queue.enqueue("c",3); queue.enqueue("d",4); queue.print();