Queue using Two Stacks

  • + 0 comments

    JS

    function processData(input) {
        const queue = {
            inbound: [],
            outbound: [],
            enqueue(data) {
                this.inbound.push(data);
            },
            dequeue() {
                if (this.outbound.length == 0) {
                    while (this.inbound.length > 0) {
                        this.outbound.push(this.inbound.pop());
                    }
                }
                return this.outbound.pop();
            },
            get() {
                return this.outbound.length ? this.outbound.at(-1) : this.inbound[0];
            }
        };
    
        input.split("\n").slice(1).forEach(query => {
            const type = query.at(0);
            if (type == "1") {
                queue.enqueue(query.split(" ")[1]);
            }
            else if (type == "2") {
                queue.dequeue();
            }
            else {
                console.log(queue.get());
            }
        });
    }