Movatterモバイル変換


[0]ホーム

URL:


HackerNoon LogoSia Logo
Backed up and published onsia.hackernoon.com.
Meta DataMeta Data Link
Featured

The Little Guide of Queue in JavaScript

Written by@germancutraro | Published on2018-02-05T17:03:27.199Z

TL;DR →

A queue is a simple <strong>data structure</strong> that allows elements to be inserted from one end, called the rear (also called tail), and deleted from the other end, called the front (also called head).

A queue is a simpledata structure that allows elements to be inserted from one end, called the rear (also called tail), and deleted from the other end, called the front (also called head).

This behavior is calledFIFO(First in First Out).

So, a queue is a linear data structure. A very important concept is that a queue deletes only theoldest added element.

The person that is removed was the first in the queue

Applications

Creation

So, in JavaScript doing aQueue is very simple because we can take arrays methods, likeunshift andpop.

Remember :

unshift Adds a element to the beginning of the array.pop Deletes the last element of the array.

Implementation

So the first thing that we are going to do is create a Queue constructor function with a empty array inside.

function Queue() {this.data = [];}

Remember that we use thethis keyword there because we need to pointer the object that we create.

Methods

The main methods will beadd andremove:

Queue.prototype.add = function(record) {this.data.unshift(record);}

Queue.prototype.remove = function() {this.data.pop();}

And we are going to add 3 methods more:

Queue.prototype.first = function() {return this.data[0];}

Queue.prototype.last = function() {return this.data[this.data.length - 1];}

Queue.prototype.size = function() {return this.data.length;}

So, let’s see what we get:

const q = new Queue():q.add(1);q.add(2);q.add(3);console.log(q);

So, the oldest one is the element with the value of1 because we added it first.

If you don’t believe me, you can use ourlast method to see it:

console.log(q.first());// -> 3console.log(q.last());// -> 1

So if we use theremove method the element that will be deleted is the oldest so the 1 is out.

q.remove();console.log(q);

And we have the last method callsize

console.log(q.size())// -> 2

Return ‘‘2’’ after we delete the last element.

Complete Code:https://github.com/germancutraro/Queue-Data-Structure;

You have myGithubif you wanna follow me, i will appreciate a lot!

Thanks toSoloLearn a fantastic app!

Great courses to learn Data Structures and Algorithms: ◾Learning Data Structures in JavaScript from Scratch ◾The Coding Interview Bootcamp: Algorithms + Data Structures

Thank you 😊

Written by
@germancutraro | Software Developer
Topics & Tags
JAVASCRIPT |QUEUE |DATA-STRUCTURES |ALGORITHMS |JAVASCRIPT-DEVELOPMENT

This story onHackerNoon has a decentralized backup onSia.

Meta Data:📄


[8]ページ先頭

©2009-2025 Movatter.jp