DEV Community

loading...

Discussion on: Stack Data Structure in Javascript

Collapse
crimsonmed profile image
Médéric Burlet

I really don't understand the purpose of this. You are just creating functions that call already existing functions.

This is a typical WET ( Write Everything Twice ) behavior.

A better example would be to do a stack of object[] where you could have useful extra functions like sorting, reversing the order and more.

Working with arrays would be much faster and economic in terms of memory and speed. And for the peek function you could simply extend the prototype.

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
};

Adding the following renders your class useless as you can easily have the following:

let myStack = [2, 3, 45, 7, 9, 6]
// let's pop
console.log(myStack.pop()); // output: 6 
// our array is now: [2, 3, 45, 7, 9]
// let's add a new item
myStack.push(18);
// our array is now: [2, 3, 45, 7, 9, 18]
// let's use the prototype extension mentioned earlier
console.log(myStack.last()); // output: 18
// you could then do things like
myStack.reverse()
// this reverses our stack

A faster way that you could also peek would be:

$this.data.reduceRight(a => a);