types/stack.js

import {Monster, Base} from './base.js';

/**
 * Stack class
 *
 * you can call the method via the monster namespace `new Monster.Types.Queue()`.
 *
 * ```
 * <script type="module">
 * import {Monster} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.5.0/dist/modules/types/stack.js';
 * console.log(new Monster.Types.Stack())
 * </script>
 * ```
 *
 * Alternatively, you can also integrate this function individually.
 *
 * ```
 * <script type="module">
 * import {ID} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.5.0/dist/modules/types/stack.js';
 * console.log(new Stack())
 * </script>
 * ```
 *
 * @since 1.4.0
 * @copyright schukai GmbH
 * @memberOf Monster/Types
 */
class Stack extends Base {

    /**
     *
     */
    constructor() {
        super();
        this.data = [];
    }


    /**
     * @return {boolean}
     */
    isEmpty() {
        return this.data.length === 0;
    }

    /**
     * looks at the object at the top of this stack without removing it from the stack.
     *
     * @return {*}
     */
    peek() {
        if (this.isEmpty()) {
            return undefined;
        }

        return this.data?.[this.data.length - 1];
    }

    /**
     * pushes an item onto the top of this stack.
     *
     * @param {*} value
     * @returns {Queue}
     */
    push(value) {
        this.data.push(value)
        return this;
    }

    /**
     * remove all entries
     *
     * @returns {Queue}
     */
    clear() {
        this.data = [];
        return this;
    }

    /**
     * removes the object at the top of this stack and returns
     * that object as the value of this function. is the stack empty
     * the return value is undefined.
     *
     * @return {*}
     */
    pop() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.data.pop();
    }


}

Monster.assignToNamespace('Monster.Types', Stack);
export {Monster, Stack}