What is the use of e in this code? Also how is this.add preventing duplicate values

function mySet(){

var collection = [];

this.has = function(element){

    return (collection.indexOf(element) !== -1)

}

this.values = function(){

    return collection;

}

this.add = function(element){

    if(!this.has(element)){

        collection.push(element);

        return true;

    }

this.remove = function(element){

    if(this.has(element)){

        index = collection.indexOf(element);

        collection.splice(index, 1);

        return true;

    }

    return false;

}

this.size = function(){

    return collection.length;

}

this.union = function(otherSet){

    var unionSet = new Set();

    var firstSet = this.values();

    var secondSet = otherSet.values();

    firstSet.forEach(function(e){

        unionSet.add(e);

    })

    secondSet.forEach(function(e){

        unionSet.add(e);

    })

    return unionSet;

}

this.difference = function(otherSeet){

    var differenceSet = new mySet();

    var firstSet = this.values();

    firstSet.forEach(function(e){

        if(!otherSet.has(e)){

            differenceSet.add(e)

        }

        return differenceSet;

    })

    this.subset = function(otherSet){

        var firstSet = this.values();

        return firstSet.every(function(value){

            return otherSet.has(value);

        })

    }

}

}

}

e in this code is being used as an event parameter. It is essentially holding an object containing the events that happened to the target.

Regarding forEach, check this link..

function(e) means that e is the argument to the function, the thing that the function takes in and acts upon.

In the case of forEach(fucntion(e){})the function specified in the brackets is going to act on (take as an argument) e, but e here is just kind of a dummy variable representing every item in the array (the forEach will do the function once on each entry of the array). Again, see the linked example if unclear.

1 Like