Created
May 3, 2019 00:46
-
-
Save DavidWells/fcae2e8ac9d4fb65bdfc06d4f00078f7 to your computer and use it in GitHub Desktop.
Vanilla JS queue
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
export default function Queue(initialValue = []) { | |
// initialise the queue and offset | |
var queue = initialValue | |
var offset = 0 | |
// Returns the the queue. | |
this.get = function() { | |
return queue | |
} | |
// Returns the length of the queue. | |
this.getLength = function() { | |
return (queue.length - offset) | |
} | |
// Returns true if the queue is empty, and false otherwise. | |
this.isEmpty = function() { | |
return (queue.length === 0) | |
} | |
/* Enqueues the specified item. The parameter is: | |
* | |
* item - the item to enqueue | |
*/ | |
this.enqueue = function(item) { | |
queue.push(item) | |
} | |
/* Dequeues an item and returns it. If the queue is empty, the value | |
* 'undefined' is returned. | |
*/ | |
this.dequeue = function() { | |
// if the queue is empty, return immediately | |
if (!queue.length) return undefined | |
// store the item at the front of the queue | |
var item = queue[offset] | |
// increment the offset and remove the free space if necessary | |
if (++offset * 2 >= queue.length) { | |
queue = queue.slice(offset) | |
offset = 0 | |
} | |
// return the dequeued item | |
return item | |
} | |
/* Returns the item at the front of the queue (without dequeuing it). If the | |
* queue is empty then undefined is returned. | |
*/ | |
this.peek = function() { | |
return (queue.length > 0 ? queue[offset] : undefined) | |
} | |
} |
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
import Queue from './queue' | |
const seed = localStorage.getItem(PERSISTANCE) || [] | |
const queue = new Queue(seed) | |
const firstItemFromQueue = queue.dequeue() | |
// do stuff with firstItemFromQueue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment