TypeScript Queue Sandbox

Written as a proof-of-concept for a general use FIFO Queuing mechanism.

by David Kyle

TypeScript

interface IQueueItem {
  work(delegate : () => void): void;
}

class WorkQueue {
  private items: any[];
  private queueInterval: number;
  private queueTimer: any;
  private currentlyProcessing: string;
  private queueListening: boolean;

  public constructor(interval: number) {
    this.items = [];
    this.queueTimer = null;
    this.queueInterval = interval;
    this.currentlyProcessing = '';
    this.queueListening = false;
  }

  /**
   * Generates a unique identifier, similar to a GUID so we can easily keep track of unique items in the queue.
   */
  private generateId(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      // tslint:disable: one-variable-per-declaration
      // tslint:disable-next-line: no-bitwise
      const r = Math.random() * 16 | 0,
        // tslint:disable-next-line: no-bitwise
        v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  /**
   * Processes the queue on an interval.
   */
  private processQueue(): void {
  console.log(this.queueTimer);
    console.log('processing');
    if (this.items && this.items.length > 0) {
      console.log(this.items.length);
      if (this.currentlyProcessing === '') {
        this.processQueueItem(() => {
          this.currentlyProcessing = '';
        });
      }
    } else {
      console.log('done');
      clearInterval(this.queueTimer);
      this.queueTimer = null;
      this.queueListening = false;
    }
  } // end method processQueue

  /**
   * Processes an item in the queue (if any).
   */
  private processQueueItem(onComplete: () => void): void {
    this.currentlyProcessing = '1'; // mark it as processing to avoid the queue stepping on it's own toes before we get actual data in
    const itemToQueue = this.items.splice(0, 1)[0];
    this.currentlyProcessing = itemToQueue.id;
    itemToQueue.operation.work(onComplete.bind(this));
  }

  private startListening(): void {
      console.log('starting listener');
    if...