📦Stack

🚧 under construction

data structure ⟩ Stack

implementations

// ⭐ Stack
//    2022.12.28 - ??:?? - first version
// ----------------------------
// 🔹 .push(a, b, c ...)
// 🔹 .pop()
// 🔹 .enqueue(a, b, c ...)    // speaks in Queue's language
// 🔹 .dequeue()               // (same)
// 🔸 .first
// 🔸 .length
// 🔸 .isEmpty
// ----------------------------
// 🔹 .toString()
// 🔹 .log()
//
class Stack {

    // 🔸 private members
    #elements = [];    // stack elements
    
    // ⭐ const q = new Queue(a, b, c ...)
    constructor(...elements) {
        this.push(...elements);
    }
    
    // 🔹 stack.push(a, b, c ...)
    push(...elements) {
        for (const element of elements) {
            this.#elements.push(element);
        }
    }
    
    // 🔹 stack.pop()
    pop() {
        if (this.isEmpty) return null;
        return this.#elements.pop();
    }
    
    // 🔸 stack.first
    get first() {
        if (this.isEmpty) return null;
        return this.#elements[this.length - 1];
    }
    
    // 🔸 stack.length
    get length() {
        return this.#elements.length;
    }
    
    // 🔸 stack.isEmpty
    get isEmpty() {
        return this.length === 0;
    }

    // 🔹 stack.toString()
    toString() {
        return `Stack: [${this.#elements} ->`;
    }

    // -----------------------------
    //   speak in Queue's language
    // -----------------------------

    enqueue(...elements) { this.push(...elements) }
    dequeue() { return this.pop() }

    // -------------
    //   dubugging
    // -------------

    // 🔹 .log()
    log() { console.log(this.toString()) }

    // 🔸 .debugInfo
    get debugInfo() { return '' }
}

module.exports = { Stack };

Last updated