UNPKG

cb-buffer

Version:

A minimalist NodeJS module for callback buffering.

138 lines (116 loc) 3.72 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"); } } module.exports = function () { /** * CbBuffer * Creates a new instance of `CbBuffer`. * * The instance will contain methods documented below and the following fields: * * - `buffer` (Array): An array of functions to be called. * - `waiting` (Boolean): A flag representing the state of the buffer. * - `is_done` (Boolean): A flag representing the done state (is done or not). * - `args` (Array): The callback function arguments. * * @name CbBuffer * @function * @return {CbBuffer} The `CbBuffer` instance. */ function CbBuffer() { _classCallCheck(this, CbBuffer); // The functions buffer this.buffer = []; this.undone(); } /** * check * Use this function to append the new function and `return` if needed: * * ```js * if (cb.check(callback)) { return; } * ``` * * @name check * @function * @param {Function} fn The callback function. * @return {Boolean} `true` if thw async function was called already. */ _createClass(CbBuffer, [{ key: "check", value: function check(fn) { if (this.is_done) { this.call(fn); return true; } this.buffer.push(fn); if (this.waiting) { return true; } else { this.waiting = true; } return false; } /** * call * Calls the provided function with the callback arguments. * * @name call * @function * @param {Function} fn The function to call. */ }, { key: "call", value: function call(fn) { fn.apply(this, this.args); } /** * clear * CLears the callback array. * * @name clear * @function */ }, { key: "clear", value: function clear() { this.buffer = []; } /** * undone * Resets the internal data. * * @name undone * @function */ }, { key: "undone", value: function undone() { // Waiting: false/true this.waiting = false; // Is done: false/true this.is_done = false; // This will be the callback arguments array this.args = []; } /** * done * Calls all the functions from the buffer. * * @name done * @function */ }, { key: "done", value: function done() { var _this = this; this.is_done = true; this.args = arguments; this.buffer.forEach(function (fn) { return _this.call(fn); }); this.clear(); } }]); return CbBuffer; }();