/queue-ts

Typescript queue data structure

Primary LanguageTypeScriptGNU General Public License v3.0GPL-3.0

Optimized Typescript queue

I was working on a javascript / typescript challenge and noticed there is no inbuilt queue data structure.

So here is one to copy and paste for your projects.

Neatly documented to make learning easier.

What is a queue?

A queue is a First-In-First-Out (FIFO) data structure where the first element added to the queue is the first one to be removed.

How is it used?

import * from "any/Queue.ts" // Import a queue that can accept all types.

new Queue([OPTIONAL ARGUMENTS]) // Create a new queue. With optional list of elements.

OR

import * from "generic/Queue.ts" // Import a queue of defined type.

new Queue<Type>([OPTIONAL ARGUMENTS]) // Create a new queue of type Type. With optional list of elements.

THEN

enqueue(element); // Add a new element to the end of the queue.

dequeue(); // Remove the element from the front of the queue and return it.

peek(); // Return the element from the front of the queue.
Queue data structure illustration. Credit to Vegpuff.

Why not use the javascript / typescript array.push(element) and array.shift() methods?

That is a good question.

The default array.shift() method works the same as dequeue(),

However every array.shift() call rebuilds the array and has an O(n) complexity, leading to slow performance for large queues.

Here dequeue() is an O(1) operation up to a given limit, which you can edit.