All files / zyspawn blocking-queue.js

80% Statements 12/15
100% Branches 4/4
71.43% Functions 5/7
80% Lines 12/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72                    18x 18x               5x               1x                   30777x 29720x   1057x                   31777x 2057x   29720x 29720x                               4x  
/**
 * @fileoverview
 * This module defines BlockingQueue (see below).
 */
 
/**
 * A blocking queue which pends get request utill an item becomes available.
 */
class BlockingQueue {
    constructor() {
        this._items = [];
        this._blockedJobs = [];
    }
 
    /**
     * Get item number.
     * @return {number} Current number of items in the queue
     */
    size() {
        return this._items.length;
    }
 
    /**
     * Get number of blocked jobs.
     * @return {number} Current number of items in the queue
     */
    waitingCount() {
        return this._blockedJobs.length;
    }
 
    /**
     * Get an item from the queue. The callback will be called when an item
     * is available.
     * @param {function(Error, any)} callback Called when item is avaible or
     *                                        clearWaiting() is called.
     */
    get(callback) {
        if (this._items.length == 0) {
            this._blockedJobs.push(callback);
        } else {
            callback(null, this._items.shift());
        }
    }
 
    /**
     * Put an item in the queue. If there are blocked jobs, the first of them
     * will be called.
     * @param {any} item The item to put
     */
    put(item) {
        if (this._blockedJobs.length == 0) {
            this._items.push(item);  
        } else {
            let callback = this._blockedJobs.shift();
            callback(null, item);
        }
    }
 
    /**
     * Raise an error on each waiting get requests.
     * @param {Error} err The error to raise
     */
    clearWaiting(err) {
        this._blockedJobs.forEach((callback) => {
            callback(err);
        });
        this._blockedJobs.length = 0;
    }
}
 
module.exports = BlockingQueue;