@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.
120 lines (119 loc) • 3.41 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stack = void 0;
const NodeClass_1 = require("./NodeClass");
const StackException_1 = require("./StackException");
class Stack {
constructor(capacity = Infinity) {
this.top = null;
this.count = 0;
this.capacity = capacity;
}
push(item) {
if (this.stackIsFull()) {
throw new StackException_1.StackException("The stack is full!");
}
this.top = new NodeClass_1.NodeClass(item, this.top);
++this.count;
}
stackIsEmpty() {
return this.top === null;
}
stackIsFull() {
return this.count >= this.capacity;
}
pop() {
if (this.stackIsEmpty()) {
throw new StackException_1.StackException("The stack is empty!");
}
--this.count;
this.top = this.top.link;
}
peek() {
if (this.stackIsEmpty()) {
throw new StackException_1.StackException("The stack is empty!");
}
return this.top.item;
}
poll() {
const elem = this.peek();
this.pop();
return elem;
}
size() {
return this.count;
}
reverse() {
let previous = null;
let current = this.top;
while (current !== null) {
const next = current.link;
current.link = previous;
previous = current;
current = next;
}
this.top = previous;
}
toArray() {
const result = [];
for (let node = this.top; node !== null; result.push(node.item), node = node.link)
;
return result;
}
toArrayReversed() {
return this.toArray().reverse();
}
fromArray(arr, preserveOrder = false, capacity = Infinity) {
const stack = new Stack(capacity);
const src = preserveOrder ? [...arr].reverse() : arr;
for (let elem of src) {
stack.push(elem);
}
return stack;
}
clone() {
const stackClone = new Stack(this.capacity);
for (let node = this.top; node !== null; stackClone.push(node.item), node = node.link)
;
stackClone.reverse();
return stackClone;
}
equals(otherStack) {
if (this.size() !== otherStack.size()) {
return false;
}
const cloneA = this.clone();
const cloneB = otherStack.clone();
while (!cloneA.stackIsEmpty() && !cloneB.stackIsEmpty()) {
if (cloneA.poll() !== cloneB.poll()) {
return false;
}
}
return true;
}
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.top; node !== null; node = node.link) {
const key = String(node.item);
freq[key] = (freq[key] ?? 0) + 1;
}
return freq;
}
toString() {
let sb = [];
for (let node = this.top; node !== null; node = node.link) {
sb.push(node.item.toString());
sb.push(" ");
}
return sb.join("").trim();
}
clear() {
this.top = null;
this.count = 0;
}
}
exports.Stack = Stack;