UNPKG

@monocircuit/utils

Version:

A repository that contains data structures, algorithms and more.

102 lines 3.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList_1 = require("../LinkedList/LinkedList"); /** * A linear data structure that is build in a fashion that mostly exposes a * BigO notation of `O(1)` * * It follows the principle of LIFO (Last In First Out). * * @spacecomplexity `O(n)` */ var Stack = /** @class */ (function () { /** * @param options Options that affect the initialization process of the `Stack`. */ function Stack(options) { this.__linkedList = new LinkedList_1.default(options); } Object.defineProperty(Stack.prototype, "length", { /** * Returns the amout of elements found on the `Stack`. * @returns The length of the `Stack` */ get: function () { return this.__linkedList.length; }, enumerable: false, configurable: true }); /** * Checks wether or not the `Stack` does not contain any elements. This * works based on the `LinkedList` implementation. * * @returns A boolean that indicates wether or not the `Stack` is empty */ Stack.prototype.isEmpty = function () { return this.__linkedList.isEmpty(); }; /** * Fetches the element that currently sits on top of the `Stack`. * * @returns The data that the top most element holds */ Stack.prototype.peek = function () { if (this.isEmpty()) { return null; } return this.__linkedList.head.data; }; /** * Adds a new element with some data to the top of the `Stack`. * * @param data A piece of data that will be held by the element on the `Stack` * @returns The `Stack` instance */ Stack.prototype.push = function (data) { this.__linkedList.prepend(data); return this; }; /** * Deletes the top most element of the `Stack`. * * @returns The data that the deleted element held, or nothing if the `Stack` was empty. */ Stack.prototype.pop = function () { var removedHead = this.__linkedList.deleteHead(); return removedHead ? removedHead.data : null; }; /** * Converts the `Stack` to an array. The indices are converted as to be * expected. * * @returns An array containing the elements of the `Stack` */ Stack.prototype.toArray = function () { return this.__linkedList.toArray(false).map(function (node) { return node.data; }); }; /** * Prepends an array to the `Stack` instance. * * @param data An array of data that will be put on the `Stack` * @returns The `Stack` instance */ Stack.prototype.fromArray = function (data) { for (var i = data.length - 1; i >= 0; i -= 1) { this.push(data[i]); } return this; }; /** * Converts the `Stack` to string. * * @param callback A function that will handle the stringification * @returns A string containg the stringified data of the stack's elements. */ Stack.prototype.toString = function (callback) { return this.__linkedList.toString(callback); }; return Stack; }()); exports.default = Stack; //# sourceMappingURL=Stack.js.map