npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

elegant-queue

v1.0.7

Published

To address this inefficiency when processing large amounts of data, designing a queue with O(1) time complexity can solve many problems.

Downloads

12

Readme

elegant-queue

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");

ES Modules

import { Queue } from "elegant-queue";

🔎 Explore features

constructor(arraySize: number)

arraySize: number (optional): This parameter defines the size of each internal array block within the linked nodes of the queue. It specifies how many elements each node in the queue can hold. By default, this value is set to 4096 if no argument is provided.

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]

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);
    }
}

⚡️ 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');

Array Queue performance result:

  console.time
    ArrayQueue Dequeue Time: 109907 ms

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');

Elegant Queue performance result:

  console.time
    ElegantQueue Dequeue Time: 5 ms

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.