So I read and have only used the new
keyword with classes and constructor functions.
However I am seeing in the JS Data Structures… that there is no class or constructer function, but only a function with all the method functions located inside of it… create an empty obj with new
keyword… I though you could only use new
with classes/constructors. See at the bottom where the new
is uses.
function mySet() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new mySet();
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 method will test if the set is a subset of a different set
this.subset = function(otherSet) {
var firstSet = this.values();
return firstSet.every(function(value) {
return otherSet.has(value);
});
};
}
var setA = new mySet();
var setB = new mySet();
setA.add("a");
setB.add("b");
setB.add("c");
setB.add("a");
setB.add("d");
console.log(setA.subset(setB));
console.log(setA.intersection(setB).values());
console.log(setB.difference(setA).values());
``'