javascript-algorithms
javascript-algorithms copied to clipboard
Add Circular Queue Implementation
Pull Request: Add Circular Queue Implementation
Description
This pull request introduces a new implementation of a Circular Queue in JavaScript. The Circular Queue is a linear data structure that follows the First In First Out (FIFO) principle and efficiently utilizes memory by wrapping around when the end of the array is reached.
Changes Made
- Added: A new file
CircularQueue.jsthat contains the implementation of the Circular Queue. - Implemented:
constructor(capacity): Initializes the Circular Queue with a specified capacity.isEmpty(): Checks if the queue is empty.isFull(): Checks if the queue is full.peek(): Reads the element at the front of the queue without removing it.enqueue(value): Adds a new element to the end of the queue.dequeue(): Removes the element at the front of the queue.getSize(): Returns the current size of the queue.toString(): Returns the string representation of the queue.
Motivation
The motivation behind this addition is to provide an efficient queue implementation that can handle wrap-around cases seamlessly. This is particularly useful for scenarios where memory utilization is crucial and can help in reducing memory overhead compared to a standard queue implementation.
Example Usage
import CircularQueue from './CircularQueue';
const cq = new CircularQueue(5);
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.enqueue(40);
cq.enqueue(50);
console.log(cq.toString()); // Output: "10 20 30 40 50"
cq.dequeue();
console.log(cq.peek()); // Output: 20
cq.enqueue(60);
console.log(cq.toString()); // Output: "20 30 40 50 60"
Additional Context
- Browser: Google Chrome, Version 90.0.4430.85
- Operating System: Windows 10
- Testing: The Circular Queue has been tested for various edge cases including enqueuing and dequeuing from an empty and a full queue.