UNPKG

sussy-util

Version:
119 lines (118 loc) 3.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Error_1 = require("../Error"); const _1 = require("."); class Stack { constructor(initElm = []) { this.items = new _1.ImprovedArray(...initElm); } /** * The function takes a variable number of arguments of type T and pushes them into the items array * @param {T[]} elm - T[] */ push(...elm) { this.items.push(...elm); } /** * If the stack is empty, throw an error, otherwise return the last item in the stack. * @returns The last item in the array. */ peek() { if (this.items.isEmpty()) throw new Error_1.IndexOutOfBoundsError('Stack is empty.'); return this.items[this.items.length - 1]; } /** * If the stack is empty, throw an error. Otherwise, remove the last item from the stack and return * it. * @returns The last item in the array. */ pop() { if (this.items.isEmpty()) throw new Error_1.IndexOutOfBoundsError('Stack is empty.'); return this.items.pop(); } /** * The function returns true if the stack is empty, false otherwise * @returns The method returns a boolean value. */ empty() { return this.items.isEmpty(); } toString() { return `Stack: ${this.items.toString()}`; } toArray() { return this.items.clone(); } /** * It takes the items array and converts it to a JSON string. * @returns The JSON string representation of the items array. */ toJSONString() { return JSON.stringify(this.items); } /** * Returns the number of elements in the stack. * @returns The number of elements in the stack. */ size() { return this.items.length; } /** * Returns a new stack that is a copy of the current stack. * @returns A new stack with the same elements as the current stack. */ clone() { return new Stack(this.items.clone()); } clear() { this.items.clear(); } /** * Returns a new stack that contains the reversed order of the elements in the current stack. * @returns {Stack<T>} A new stack with reversed elements. */ reverse() { const reversedArray = this.items.clone().reverse(); return new Stack(reversedArray); } /** * Removes all occurrences of a specific element from the stack. * @param {T} element - The element to be removed. * @returns {number} The number of elements removed from the stack. */ removeAll(element) { const originalSize = this.size(); this.items = new _1.ImprovedArray(...this.items.filter((item) => item !== element)); return originalSize - this.size(); } /** * Returns a new stack that contains the unique elements from the current stack. * @returns {Stack<T>} A new stack with unique elements. */ distinct() { const uniqueSet = new Set(this.items); return new Stack([...uniqueSet]); } [Symbol.iterator]() { let index = this.items.length - 1; return { next: () => { if (index >= 0) { return { value: this.items[index--], done: false, }; } else { return { value: undefined, done: true, }; } }, }; } } exports.default = Stack;