UNPKG

@studyportals/sp-hs-misc

Version:

Miscellaneous code used in HouseStark's projects

105 lines (96 loc) 3.6 kB
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"); } } /** * Offers the necessary functionality to throttle * highly concurent operations. */ //# sourceMappingURL=throttler.class.js.map var Throttler = function () { _createClass(Throttler, [{ key: "concurrencyLimit", get: function get() { return this._concurrencyLimit; } }, { key: "concurrencyCounter", get: function get() { return this._concurrencyCounter; } }, { key: "tasksQueue", get: function get() { return this._tasksQueue; } }]); function Throttler() { var concurrencyLimit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 6; _classCallCheck(this, Throttler); this._tasksQueue = []; this._concurrencyCounter = 0; this._concurrencyLimit = concurrencyLimit; } _createClass(Throttler, [{ key: "enqueueTask", value: function enqueueTask(task) { this.tasksQueue.unshift(task); this.handleTaskEnqueued(); } }, { key: "handleTaskEnqueued", value: function handleTaskEnqueued() { this.executeNextTaskIfPossible(); } }, { key: "executeNextTaskIfPossible", value: function executeNextTaskIfPossible() { if (this.concurrencyLimitNotReached()) { this.executeNextTask(); } } }, { key: "executeNextTask", value: function executeNextTask() { var _this = this; if (this.tasksQueueNotEmpty()) { this.incrementConcurrencyCounter(); var task = this.dequeueTask(); task.observe(function () { return _this.handleTaskFinished(); }); task.execute(); } } }, { key: "tasksQueueNotEmpty", value: function tasksQueueNotEmpty() { return 0 !== this.tasksQueue.length; } }, { key: "dequeueTask", value: function dequeueTask() { return this.tasksQueue.pop(); } }, { key: "handleTaskFinished", value: function handleTaskFinished() { this.decrementConcurrencyCounter(); this.executeNextTaskIfPossible(); } }, { key: "incrementConcurrencyCounter", value: function incrementConcurrencyCounter() { ++this._concurrencyCounter; } }, { key: "decrementConcurrencyCounter", value: function decrementConcurrencyCounter() { --this._concurrencyCounter; } }, { key: "concurrencyLimitNotReached", value: function concurrencyLimitNotReached() { return this.concurrencyCounter < this.concurrencyLimit; } }]); return Throttler; }();