Create a Stack Class

Create a Stack Class
0

#1

I´m trying to make this exercise but I´m not achieve to know why the test´s don´t work over the methods push,peek, etc.I know that the the collection is empty, but as you can read “// Only change code below this line” so I should not fill it as far as I understand. Anyone can help me?


function Stack() { 
    var collection = [];
    this.print = function() {
        console.log(collection);
    };
    // Only change code below this line
    this.push= function(){
        collection.push();
    }

    this.pop= function(){
        collection.pop();
        return collection[collection.length-1];
    }

    this.peek=function(){
        console.log(collection[collection.length-1]);
        return collection[collection.length-1];
    }

    this.clear= function(){
        collection=[];
        console.log(collection);
        return collection;
    }

    this.isEmpty= function(){
        if (collection==[]){
            return true;
            }else{
            return false;
            }
    }
    // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-stack-class/


#2

This will never return true. When comparing objects with == (this includes arrays), it will only evaluate to true if both sides of == refer to the same object:

var a = [1,2,3];
var b = a;
a == b; // true, since both a and b refer to the same array

Since you’re comparing collection with a fresh array every time, it will always be false.

It’s much more reliable to use the array’s length property.

    this.push= function(){
        collection.push();
    }

The push function expects a parameter.

    this.pop= function(){
        collection.pop();
        return collection[collection.length-1];
    }

You’re pop function should return the element that has been removed. Here you’re first removing the top element, then returning the value after that.