Guest User

AnsiQ.js

a guest
May 24th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * queueing is bad, hence AnsiQ
  3.  * @class
  4.  */
  5. class AnsiQ {
  6.   /**
  7.    * build the Q
  8.    * @param {ArrayObject} Q queue of commands, can be null
  9.    * @param {function (AnsiQ, ArrayObject, number)} callback function (context, element, queueId)
  10.    *                                                         function must execute context.processed or context.error
  11.    * @param {number} tickMs ms between each tick
  12.    */
  13.   constructor (Q, callback, tickMs = 500) {
  14.     this.tickMs = tickMs
  15.     this.Q = Q || []
  16.     this.fn = callback
  17.   }
  18.   /**
  19.    * sets q element processed
  20.    * @param {number} qId q element id
  21.    */
  22.   processed (qId) {
  23.     console.log('Processed', qId)
  24.     this.Q[qId] = true
  25.     return this
  26.   }
  27.   /**
  28.    * sets q element processing
  29.    * @param {number} qId q element id
  30.    */
  31.   processing (qId) {
  32.     console.log('Processing', qId)
  33.     this.Q[qId] = 'processing'
  34.     return this
  35.   }
  36.   /**
  37.    * sets q element error
  38.    * @param {number} qId q element id
  39.    */
  40.   error (qId) {
  41.     console.log('Error', qId)
  42.     this.Q[qId] = false
  43.     return this
  44.   }
  45.   /**
  46.    * start ticking
  47.    */
  48.   tick () {
  49.     // it's ticking!
  50.     this.ticking = true
  51.     for (let q = 0; q < this.Q.length; q += 1) {
  52.       // picks element
  53.       let elm = this.Q[q]
  54.       // true or false element completed
  55.       if (elm === true || elm === false) {
  56.         continue
  57.       }
  58.       let self = this
  59.       if (elm !== 'processing') {
  60.         // not processing, means is a q element
  61.         console.log('tick', q)
  62.         this
  63.           // sets the element processing
  64.           .processing(q)
  65.           // calls the callback
  66.           .fn(self, elm, q) // @todo: for some weird reason .call & .apply don't sets 'this' in the called function
  67.       }
  68.       return setTimeout(function () {
  69.         self.tick()
  70.       }, this.tickMs)
  71.     }
  72.     // no more ticking
  73.     this.ticking = false
  74.     return true
  75.   }
  76.   /**
  77.    * q an element in the Q
  78.    * queueing an element starts the Q
  79.    * @param {any} element will be later passed to the callback
  80.    */
  81.   queue (element) {
  82.     this.Q.push(element)
  83.     if (this.ticking === false) {
  84.       this.tick()
  85.     }
  86.   }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment