Last active
August 22, 2019 21:45
-
-
Save EnzoDiazDev/fe7476d98e65df4d9365af0cc65028e8 to your computer and use it in GitHub Desktop.
Queue structure written in Javascript, using class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Queue { | |
constructor(type = "any", maxSize = Infinity){ | |
if(typeof type === "number"){ | |
maxSize = type | |
type = "any" | |
} | |
if(Number(type) && maxSize == Infinity){ | |
maxSize = Number(type) | |
type = "any" | |
} | |
if(typeof maxSize != "number"){ | |
if(Number(maxSize)) maxSize = Number(maxSize) | |
else maxSize = Infinity | |
} | |
type = type.toLowerCase() | |
this.type = (type != "string" && | |
type != "number" && | |
type != "object" && | |
type != "boolean" | |
) ? "any" : type.toLowerCase() | |
this.maxSize = maxSize | |
this.values = [] | |
} | |
enqueue(item){ | |
if(!item) return | |
else { | |
if(this.type != "any") if(typeof item != this.type) throw new Error(`Item must be a ${this.type}`) | |
if(this.values.length >= this.maxSize) throw new Error(`Queue is full. Max: ${this.maxSize}`) | |
else this.values.push(item) | |
} | |
} | |
dequeue(){ | |
if(!this.values.length) throw new Error(`Queue is empty.`) | |
else { | |
let firstValue = this.values.splice(0,1)[0] | |
return firstValue | |
} | |
} | |
peek(){ | |
if(!this.values.length) throw new Error(`Queue is empty.`) | |
else return this.values[0] | |
} | |
length(){ | |
return this.values.length | |
} | |
isEmpty(){ | |
if(!this.values.length) return true | |
else return false | |
} | |
isFull(){ | |
if(this.values.length == this.maxSize) return true | |
else return false | |
} | |
} | |
//Se crea una nueva cola llamada clientes la cual permite solo 3 de ellos. | |
let clients = new Queue("string", 3) | |
//Se añaden dos elementos. | |
clients.enqueue("Juan") | |
clients.enqueue("Pedro") | |
//Juan y Pedro ahora se encuentran en la cola, podemos visualizar cuántos 'clientes' se encuentran en la cola | |
console.log("Cantidad de clientes:", clients.length(), "\n") | |
//Veamos quién fue el primer cliente en entrar | |
console.log("El primer cliente en entrar fue:", clients.peek(), "\n") | |
//Agreguemos a Manuelita a la cola | |
clients.enqueue("Manuelita") | |
//Veamos ahora cuántos clientes hay | |
console.log("Cantidad de clientes:", clients.length(), "\n") | |
//Vamos a atender al primer cliente, y por ende, a eliminarlo de la cola | |
let client = clients.dequeue() | |
console.log(`El cliente ${client} ha sido atendido.\nSiguente en la cola:`, clients.peek(), "\n") | |
//Dos clientes más se acercan a la caja, son Simón y Pepita | |
clients.enqueue("Simón") | |
clients.enqueue("Pepita") //Error: Queue is full. Max: 3 | |
//Esto nos arroja error debido a que Pepita excede el límite de la cola. Solo Simón es capaz de entrar por ser el primero en llegar. | |
//Si consideramos que Simón es el límite, podemos comprobar si la cola está llena | |
console.log("¿La cola está llena?", clients.isFull(), "\n") | |
//Atendamos a los demás clientes | |
clients.dequeue() | |
clients.dequeue() | |
clients.dequeue() | |
//Revisemos cuántos clientes hay en la cola y veamos si ésta está vacía | |
console.log("Cantidad de clientes:", clients.length()) | |
console.log("¿La cola está vacía?", clients.isEmpty()) | |
//Eliminemos otro elemento ahora que está vacía | |
clients.dequeue() //Error: Queue is empty. | |
//Esto nos arroja error debido a que ya no hay más elementos que eliminar. | |
//Agrueguemos un objeto a la cola | |
let dummy = { | |
name: "John Doll", | |
material: "Plush" | |
} | |
clients.enqueue(dummy) //Error: Item must be a string | |
//Esto nos arroja un error debido a que 'dummy' es un tipo objeto, cuando nuestra cola sólo permite strings. | |
//Es posible crear una nueva cola únicamente para muñecos, indicando el tipo de dato como 'object', o una cola más inclusiva que acepte todo tipo de dato simplemente con ignorar el parametro 'type' | |
let allClients = new Queue(5) | |
allClients.enqueue(dummy) | |
allClients.enqueue("Pepita") | |
//También es posible ignorar el tamaño de la cola para que ésta sea sencillamente infinita. | |
let bankQueue = new Queue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment