UNPKG

queoid

Version:

A stupid simple and low-level queue library.

127 lines (102 loc) 3.36 kB
"use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Queoid = function () { /** * Queoid * Creates a new function queue. * * @name Queoid * @function * @param {Function} fn The function to call when the queue is ended. */ function Queoid(fn) { _classCallCheck(this, Queoid); this._q = []; this._start = null; this._ended = false; this._result = []; this._running = false; if (fn) { process.nextTick(this.start, fn); } } /** * done * This function ends the queue. This is called internally (in most cases * you don't have to call it manually). * * @name done * @function */ _createClass(Queoid, [{ key: "done", value: function done() { this._ended = true; this._start(this._result); } /** * check * Checks the state of the queue and runs the next function. * * @name check * @function */ }, { key: "check", value: function check() { if (this._running) { return; } var self = this, _fn = this._q.shift(); if (!_fn) { return this.done(); } self._running = true; var cb = function cb() { self._running = false; self._result.push(arguments); self.check(); }, args = [_fn.fn].concat(_fn.args).concat([cb]); process.nextTick.apply(this, args); } /** * push * Adds a new function in the queue. * * @name push * @function * @param {Function} fn The function to push in the queue. * @param {Array} args The arguments used to call the function. */ }, { key: "push", value: function push(fn, args) { if (this._ended) { return; } this._q.push({ fn: fn, args: args || [] }); if (this._start) { this.check(); } } /** * start * Start the function queue execution. * * @name start * @function * @param {Function} fn The function to call when the queue is ended. */ }, { key: "start", value: function start(fn) { this._start = fn || function () {}; this.check(); } }]); return Queoid; }(); module.exports = Queoid;