DEV Community

Discussion on: Stacks and Queues — BaseCS Video Series

Collapse
 
nonsobiose profile image
Nonso Biose

Hey, when you say an Array is a static Data Structure, I understand, coz in Java an array is created with an initial size. But in javaScript, arrays are dynamic. So can't see implement a stack using arrays in JavaScript.

Collapse
 
namirsab profile image
Namir

You can easily do it with arrays. A small example:

class Stack {
    constructor() {
        this.stack = [];
    }
    push(element) {
        this.stack.push(element);
    }
    top() {
        return this.stack[this.stack.length - 1];
    }

    pop() {
        return this.stack.pop();
    }

    toArray() {
        return Array.from(this.stack);
    }

    isEmpty() {
        return this.stack.length === 0;
    }
}

You could tune it a bit to check for a maximum size or stuff like that :)

Collapse
 
nonsobiose profile image
Nonso Biose

Thanks. But in this way, the stack can never get filled up, coz the array ain't static. I think different languages, have their different implementation of abstract structures. In java, you can't implement a stack with an array coz its fixed

Thread Thread
 
namirsab profile image
Namir

You can always "fix" the array if you want by adding a size to the constructor. Then you check if the size is met whenever you push a new value to the stack. So yeah, the language can give you other constructs and other ways to do something, but it's totally possible to do it in JavaScript

Thread Thread
 
nonsobiose profile image
Nonso Biose

Thanks man