DEV Community

Discussion on: JavaScript Data Structures: Stack: Push / Add a new node

Collapse
 
jannikwempe profile image
Jannik Wempe

Hi, I love this series. I always try to implement it by myself first.

Came up with a slight improvement of the push function:

// ....
push(value) {
    const newNode = new Node(value);

    if (this.length) newNode.next = this.lastNode;
    this.lastNode = newNode;
    this.length++;
    return this;
  }
// ...
Enter fullscreen mode Exit fullscreen mode

I also like to return the whole object for the possibility of chaining the function:

const myStack = new Stack();
myStack
.push("a")
.push("b")
.push("c");
Enter fullscreen mode Exit fullscreen mode

Keep on doing this series. Love it! :-)

Collapse
 
miku86 profile image
miku86

Hey Jannik,

thanks for your feedback,
I appreciate it.

You are right, there is some duplication.
I wanted to stay consistent with the Thoughts section,
therefore I implemented it my way.

Greetings
Michael