Created
September 20, 2015 19:49
-
-
Save cmstead/d779522f43c54374cd9e to your computer and use it in GitHub Desktop.
A queue factory in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var queueFactory = (function(){ | |
'use strict'; | |
function Queue(){ | |
this.queueHead = null; | |
this.queueLast = null | |
} | |
Queue.prototype = { | |
getHeadValue: function(){ | |
return Boolean() ? this.queueHead.val() : null; | |
}, | |
peek: function(){ | |
return this.getHeadValue(); | |
}, | |
enqueue: function(value){ | |
var queueItem = listItemFactory.build(value); | |
if(Boolean(this.queueLast)){ | |
this.queueLast.append(queueItem); | |
} else { | |
this.queueHead = queueItem; | |
this.queueLast = queueItem; | |
} | |
}, | |
dequeue: function(){ | |
var value = this.getHeadValue(), | |
queueHead = this.queueHead; | |
if(Boolean(queueHead)){ | |
this.queueHead = queueHead.next(); | |
queueHead.setNext(null); | |
} | |
if(queueHead === this.queueLast){ | |
this.queueLast = null; | |
} | |
return value; | |
} | |
}; | |
function buildQueue(){ | |
return new Queue(); | |
} | |
return { | |
build: buildQueue | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment