all files / src/ index.js

100% Statements 22/22
100% Branches 6/6
100% Functions 1/1
100% Lines 17/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42                              10× 10×   10× 10× 10× 12× 10×             10×      
/*
    Queue.js
 
    A function to represent a queue.
    A queue is a first-in-first-out (FIFO) data structure -
    items are added to the end of the queue and removed from the front.
 
    Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
    the terms of the CC0 1.0 Universal legal code:
    http://creativecommons.org/publicdomain/zero/1.0/legalcode
 
    Readapted by Marcelino Braulio - http://marceli.no
*/
 
function Queue() {
 
    this.queue = []
    this.offset = 0
 
    this.length = () => ( this.queue.length - this.offset )
    this.isEmpty = () => ( this.queue.length === 0 )
    this.peek = () => ( this.queue[this.offset] )
    this.enqueue = (item) => ( this.queue.push(item) )
    this.dequeue = () => {
        if (this.queue.length === 0) return undefined
 
        const item = this.queue[this.offset]
        if (++this.offset * 2 >= this.queue.length) {
            this.queue = this.queue.slice(this.offset)
            this.offset = 0
        }
        return item
    }
}
 
export default (extend) => {
    if (extend) {
        return Queue.call(extend)
    }
    return new Queue()
}