@lucadani7/algonodejs-for-beginners
Version:
Just a simple Node.js package with some basic algorithms perfect for people just starting out. It's got easy-to-understand TypeScript versions of stuff like sorting, searching, math with numbers, and messing with strings.
117 lines (116 loc) • 3.35 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
const NodeClass_1 = require("./NodeClass");
const QueueException_1 = require("./QueueException");
class Queue {
constructor(capacity = Infinity) {
this.front = null;
this.rear = null;
this.count = 0;
this.capacity = capacity;
}
enqueue(item) {
if (this.queueIsFull()) {
throw new QueueException_1.QueueException("The queue is full!");
}
const node = new NodeClass_1.NodeClass(item, this.front);
if (this.rear === null) {
this.front = this.rear = node;
}
else {
this.rear.link = node;
this.rear = node;
}
++this.count;
}
dequeue() {
if (this.queueIsEmpty()) {
throw new QueueException_1.QueueException("The queue is empty!");
}
const value = this.front.item;
this.front = this.front.link;
if (this.front === null) {
this.rear = null;
}
--this.count;
return value;
}
peek() {
if (this.queueIsEmpty()) {
throw new QueueException_1.QueueException("The queue is empty!");
}
return this.front.item;
}
poll() {
const elem = this.peek();
this.dequeue();
return elem;
}
queueIsEmpty() {
return this.front === null;
}
queueIsFull() {
return this.count >= this.capacity;
}
size() {
return this.count;
}
clone() {
const queueClone = new Queue(this.capacity);
for (let node = this.front; node !== null; queueClone.enqueue(node.item), node = node.link)
;
return queueClone;
}
equals(otherQueue) {
if (this.size() !== otherQueue.size()) {
return false;
}
const cloneA = this.clone();
const cloneB = otherQueue.clone();
while (!cloneA.queueIsEmpty() && !cloneB.queueIsEmpty()) {
if (cloneA.poll() !== cloneB.poll()) {
return false;
}
}
return true;
}
clear() {
this.front = null;
this.rear = null;
this.count = 0;
}
toArray() {
const result = [];
for (let node = this.front; node !== null; result.push(node.item), node = node.link)
;
return result;
}
toArrayReversed() {
return this.toArray().reverse();
}
fromArray(arr, preserveOrder = true, capacity = Infinity) {
const queue = new Queue(capacity);
const src = preserveOrder ? arr : [...arr].reverse();
for (const elem of src) {
queue.enqueue(elem);
}
return queue;
}
existsCertainValue(valueToSearch, compareFn) {
const comparer = compareFn ?? ((a, b) => a === b);
return this.toArray().some(elem => comparer(elem, valueToSearch));
}
getFrequencyRecord() {
const freq = {};
for (let node = this.front; node !== null; node = node.link) {
const key = String(node.item);
freq[key] = (freq[key] ?? 0) + 1;
}
return freq;
}
toString() {
return this.toArray().map(x => x.toString()).join("");
}
}
exports.Queue = Queue;