a fifo reader in javascript

Here's an example of a FIFO reader implemented in JavaScript using a queue data structure:

index.tsx
class Queue {
  constructor() {
    this.items = [];
  }
  
  enqueue(item) {
    this.items.push(item);
  }
  
  dequeue() {
    if (this.isEmpty()) {
      return "Underflow";
    }
    return this.items.shift();
  }
  
  front() {
    if (this.isEmpty()) {
      return "No items in Queue";
    }
    return this.items[0];
  }
  
  isEmpty() {
    return this.items.length === 0;
  }
  
  clear() {
    this.items = [];
  }
}

const myQueue = new Queue();

// Add items to the queue
myQueue.enqueue("A");
myQueue.enqueue("B");
myQueue.enqueue("C");
myQueue.enqueue("D");

// Read items from the queue
console.log(myQueue.dequeue()); // Output: A
console.log(myQueue.dequeue()); // Output: B

// Add more items
myQueue.enqueue("E");

console.log(myQueue.dequeue()); // Output: C
console.log(myQueue.front()); // Output: D
console.log(myQueue.dequeue()); // Output: D

// Clear the queue
myQueue.clear();

console.log(myQueue.isEmpty()); // Output: true
955 chars
56 lines

In the example above, we define a Queue class with methods to enqueue and dequeue items from the queue. We also have methods to check if the queue is empty (isEmpty), to get the front item in the queue (front), and to clear the queue (clear). We use these methods to read items from the queue in a FIFO (First In First Out) order.

gistlibby LogSnag