The encapsulation of the queue by the javscript data structure, the problem of drumming and passing flowers
function Queue ( ) {
this . items = [ ] ;
Queue. prototype. enqueue = function ( element) {
this . items. push ( element) ;
}
Queue. prototype. dequeue = function ( ) {
return this . items. shift ( )
}
Queue. prototype. front = function ( ) {
return this . items[ 0 ]
}
Queue. prototype. isEmpty = function ( ) {
return this . items. length == 0
}
Queue. prototype. size = function ( ) {
return this . items. length
}
Queue. prototype. toString = function ( ) {
return this . items. join ( " " )
}
}
function passgame ( nums, e) {
var queue = new Queue ( ) ;
for ( var i= 0 ; i< nums. length; i++ ) {
queue. enqueue ( nums[ i] ) ;
}
while ( queue. size ( ) > 1 ) {
for ( var i= 0 ; i< e- 1 ; i++ ) {
queue. enqueue ( queue. dequeue ( ) )
}
queue. dequeue ( ) ;
}
var end = queue. front ( )
return nums. indexOf ( end)
}
console. log ( passgame ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] , 5 ) ) ;
priority queue
function Priority ( ) {
function QueueElement ( element, priority) {
this . element = element;
this . priority = priority;
}
this . items = [ ]
Priority. prototype. enqueue = function ( element, priority) {
var quueElement = new QueueElement ( element, priority) ;
if ( this . items. length == 0 ) {
this . items. push ( quueElement) ;
} else {
var added = false
for ( var i = 0 ; i < this . items. length; i++ ) {
if ( quueElement. priority< this . items[ i] . priority) {
this . items. splice ( i, 0 , quueElement) ;
this . added = true ;
break ;
}
}
if ( ! added) {
this . items. push ( quueElement) ;
}
}
}
Priority. prototype. dequeue = function ( ) {
return this . items. shift ( ) ;
}
Priority. prototype. front = function ( ) {
return this . items[ 0 ]
}
Priority. prototype. isEmpty = function ( ) {
return this . items. length == 0
}
Priority. prototype. size = function ( ) {
return this . items. length
}
Priority. prototype. toString = function ( ) {
var resuletString = ''
for ( let i = 0 ; i < this . items. length; i++ ) {
resuletString+= this . items[ i] . element+ "-" + this . items[ i] . priority+ " "
}
return resuletString
}
}
var pg = new Priority ( ) ;
pg. enqueue ( 'abc' , 100 )
pg. enqueue ( 'cda' , 10 )
pg. enqueue ( 'fgh' , '40' )
console. log ( pg. toString ( ) ) ;
pg. dequeue ( ) ;
console. log ( pg. toString ( ) ) ;
console. log ( pg. front ( ) ) ;