Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * queueing is bad, hence AnsiQ
- * @class
- */
- class AnsiQ {
- /**
- * build the Q
- * @param {ArrayObject} Q queue of commands, can be null
- * @param {function (AnsiQ, ArrayObject, number)} callback function (context, element, queueId)
- * function must execute context.processed or context.error
- * @param {number} tickMs ms between each tick
- */
- constructor (Q, callback, tickMs = 500) {
- this.tickMs = tickMs
- this.Q = Q || []
- this.fn = callback
- }
- /**
- * sets q element processed
- * @param {number} qId q element id
- */
- processed (qId) {
- console.log('Processed', qId)
- this.Q[qId] = true
- return this
- }
- /**
- * sets q element processing
- * @param {number} qId q element id
- */
- processing (qId) {
- console.log('Processing', qId)
- this.Q[qId] = 'processing'
- return this
- }
- /**
- * sets q element error
- * @param {number} qId q element id
- */
- error (qId) {
- console.log('Error', qId)
- this.Q[qId] = false
- return this
- }
- /**
- * start ticking
- */
- tick () {
- // it's ticking!
- this.ticking = true
- for (let q = 0; q < this.Q.length; q += 1) {
- // picks element
- let elm = this.Q[q]
- // true or false element completed
- if (elm === true || elm === false) {
- continue
- }
- let self = this
- if (elm !== 'processing') {
- // not processing, means is a q element
- console.log('tick', q)
- this
- // sets the element processing
- .processing(q)
- // calls the callback
- .fn(self, elm, q) // @todo: for some weird reason .call & .apply don't sets 'this' in the called function
- }
- return setTimeout(function () {
- self.tick()
- }, this.tickMs)
- }
- // no more ticking
- this.ticking = false
- return true
- }
- /**
- * q an element in the Q
- * queueing an element starts the Q
- * @param {any} element will be later passed to the callback
- */
- queue (element) {
- this.Q.push(element)
- if (this.ticking === false) {
- this.tick()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment