Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function MySet() {
- const collection = [];
- // check if the given element is present in the collection
- this.has = function (element) {
- return collection.indexOf(element) !== -1;
- };
- // returns all the elements in the collection
- this.values = function () {
- return collection;
- };
- // adds the given element into collection if its not present in the collection
- this.add = function (element) {
- if(!this.has(element)) {
- collection.push(element);
- return true;
- }
- return false;
- };
- // removes the given element from the collection
- this.remove = function (element) {
- if(this.has(element)) {
- collection.splice(collection.indexOf(element), 1);
- return true;
- }
- return false;
- };
- this.size = function () {
- return collection.length;
- };
- // returns all the elements from both the given sets
- this.union = function (otherSet) {
- const unionSet = new MySet();
- const primarySet = this.values();
- const secondarySet = otherSet.values();
- primarySet.forEach(function (element) {
- unionSet.add(element);
- });
- secondarySet.forEach(function (element) {
- unionSet.add(element);
- });
- return unionSet;
- };
- // returns a new set with elements which are present in both the sets
- this.intersection = function (otherSet) {
- const intersectionSet = new MySet();
- const primarySet = this.values();
- primarySet.forEach(function (element) {
- if(otherSet.has(element)) {
- intersectionSet.add(element);
- }
- });
- return intersectionSet;
- };
- // returns true if the given set is subset of other set
- this.subSet = function (otherSet) {
- const primarySet = this.values();
- return primarySet.every(function (element) {
- return otherSet.has(element);
- });
- };
- }
- const set1 = new MySet();
- set1.add(10);
- set1.add(20);
- set1.add(30);
- const set2 = new MySet();
- set2.add(10);
- set2.add(20);
- set2.add(40);
- set2.add(50);
- const unionSet = set1.union(set2);
- console.log(unionSet.values());
- const intersectionSet = set1.intersection(set2);
- console.log(intersectionSet.values());
- console.log(set1.subSet(set2));
- set1.remove(30);
- console.log(set1.subSet(set2));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement