DEV Community

Cover image for Introducing elegant-queue: An Efficient Queue Implementation in JavaScript/TypeScript
Jin.Park
Jin.Park

Posted on

Introducing elegant-queue: An Efficient Queue Implementation in JavaScript/TypeScript

elegant-queue

NPM Version Package License NPM Downloads JavaScript TypeScript

Overview

In JavaScript and TypeScript, arrays are often used to implement queues. The built-in shift() method removes the element at the zeroth index and shifts the remaining elements down, which has O(n) time complexity due to the re-indexing required.

Why Circular Buffers?

To optimize queue operations, especially with large datasets, a circular buffer is a highly effective solution. It allows both enqueue and dequeue operations to be performed in O(1) time complexity by managing elements in a fixed-size array with wrapping pointers.

Key Benefits:

  • Memory Efficiency: A circular buffer uses a fixed-size array and wraps around, eliminating the need for continuous resizing and minimizing memory overhead.
  • Consistent O(1) Performance: Operations remain constant time, avoiding the performance pitfalls of array resizing and shifting.
  • Avoids Memory Fragmentation: Efficient memory use and reduced risk of fragmentation, even with dynamic queue sizes.

📚 Getting Started

elegant-queue supports both CommonJS and ES Modules.

CommonJS

const { Queue } = require("elegant-queue");
Enter fullscreen mode Exit fullscreen mode

ES Modules

import { Queue } from "elegant-queue";
Enter fullscreen mode Exit fullscreen mode

🔎 Explore features

constructor(array: T[])

The constructor initializes a new queue with the elements from the provided array.

enqueue(value: T)

This method adds a new element to the end of the queue.

dequeue()

This method removes and returns the element at the front of the queue. If the queue is empty, it throws a EmptyQueueException.

peek()

This method returns the element at the front of the queue without removing it. If the queue is empty, it throws a EmptyQueueException.

clear()

This method clears all elements from the queue.(effectively resetting the queue to its initial state.)

size()

This method returns the number of elements currently in the queue.

isEmpty()

This method checks if the queue is empty. It returns true if _head is equal to _tail (indicating no elements are present), and false otherwise.

🌈 Examples

Usage Example

import { Queue } from "elegant-queue";

const queue = new Queue([1, 2, 3, 4, 5]);
queue.enqueue(6); // [1, 2, 3, 4, 5, 6]

const item = queue.dequeue();
console.log(item); // 1 

console.log(queue); // [2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Exception Handling Example

import { Queue, EmptyQueueException } from "elegant-queue";

try {
    const item = queue.dequeue(); // Attempt to remove the item from the queue.
    console.log('Dequeued item:', item);
} catch (error) {
    if (error instanceof EmptyQueueException) {
        console.error('Queue is empty. Cannot dequeue an item.');
    } else {
        console.error('An unexpected error occurred:', error);
    }
}
Enter fullscreen mode Exit fullscreen mode

⚡️ Performance (1 million numbers)

The following benchmarks compare elegant-queue with a standard array-based queue.

Array Queue performance:

console.time('ArrayQueue Enqueue Time');
const numbers: Array<number> = [];

for (let i = 0; i < LARGE_DATA_SIZE; i++) {
  arrayQueue.push(i);
}
console.timeEnd('ArrayQueue Enqueue Time');

console.time('ArrayQueue Dequeue Time');
while (arrayQueue.length > 0) {
  arrayQueue.shift();
}
console.timeEnd('ArrayQueue Dequeue Time');
Enter fullscreen mode Exit fullscreen mode

Array Queue performance result:

  console.time
    ArrayQueue Dequeue Time: 109907 ms
Enter fullscreen mode Exit fullscreen mode

Elegant Queue performance:

console.time('ElegantQueue Enqueue Time');
const numbers = new Array<number>();

for (let i = 0; i < LARGE_DATA_SIZE; i++) {
    numbers.push(i);
}

const elegantQueue = new Queue(numbers);
console.timeEnd('ElegantQueue Enqueue Time');

console.time('ElegantQueue Dequeue Time');
while (elegantQueue.size() > 0) {
  elegantQueue.dequeue();
}
console.timeEnd('ElegantQueue Dequeue Time');
Enter fullscreen mode Exit fullscreen mode

Elegant Queue performance result:

  console.time
    ElegantQueue Dequeue Time: 5 ms
Enter fullscreen mode Exit fullscreen mode

Note: The shift() method in arrays has O(n) time complexity due to the need to re-index elements after removal. In contrast, elegant-queue provides O(1) time complexity for both enqueue and dequeue operations by utilizing a circular buffer design, making it significantly faster for large datasets.

Top comments (0)