Skip to content

Instantly share code, notes, and snippets.

@colesnicov
Created October 11, 2022 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colesnicov/3360583581e80c403149500721e08bf7 to your computer and use it in GitHub Desktop.
Save colesnicov/3360583581e80c403149500721e08bf7 to your computer and use it in GitHub Desktop.
javascript implementation of queue with extended functionality
/*
* The MIT License
*
* Copyright 2022 denis.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// source https://www.geeksforgeeks.org/implementation-queue-javascript/
/**
*
* @type class
*/
class Queue
{
/**
*
* @returns {Queue}
*/
constructor()
{
this.items = [];
}
/**
* adding element to the queue
*
* @param {type} element
* @returns {undefined}
*/
push(element)
{
this.items.push(element);
}
/**
* removing element from the queue
* returns underflow when called
* on empty queue
*
* @returns {Object|undefined|String}
*/
pop()
{
if (this.isEmpty()) {
return "Underflow";
}
return this.items.shift();
}
/**
* returns the Front element of
* the queue without removing it.
*
* @returns {Array|String}
*/
front()
{
if (this.isEmpty()) {
return "No elements in Queue";
}
return this.items[0];
}
/**
* returns the Back element of
* the queue without removing it.
*
* @returns {Array|String}
*/
back()
{
if (this.isEmpty()) {
return "No elements in Queue";
}
return this.items[this.items.length - 1];
}
/**
* return true if the queue is empty.
*
* @returns {Boolean}
*/
isEmpty()
{
return this.items.length === 0;
}
/**
*
* @param {Function} func
* @returns {undefined}
*/
forEach(func) {
for (let i = 0; i < this.items.length; i++) {
func(i, this.items[i]);
}
}
printQueue()
{
var str = "";
for (var i = 0; i < this.items.length; i++) {
str += this.items[i] + " ";
}
return str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment