Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. function MySet() {
  2. const collection = [];
  3.  
  4. // check if the given element is present in the collection
  5. this.has = function (element) {
  6. return collection.indexOf(element) !== -1;
  7. };
  8.  
  9. // returns all the elements in the collection
  10. this.values = function () {
  11. return collection;
  12. };
  13.  
  14. // adds the given element into collection if its not present in the collection
  15. this.add = function (element) {
  16. if(!this.has(element)) {
  17. collection.push(element);
  18. return true;
  19. }
  20. return false;
  21. };
  22.  
  23. // removes the given element from the collection
  24. this.remove = function (element) {
  25. if(this.has(element)) {
  26. collection.splice(collection.indexOf(element), 1);
  27. return true;
  28. }
  29. return false;
  30. };
  31.  
  32. this.size = function () {
  33. return collection.length;
  34. };
  35.  
  36. // returns all the elements from both the given sets
  37. this.union = function (otherSet) {
  38. const unionSet = new MySet();
  39. const primarySet = this.values();
  40. const secondarySet = otherSet.values();
  41. primarySet.forEach(function (element) {
  42. unionSet.add(element);
  43. });
  44. secondarySet.forEach(function (element) {
  45. unionSet.add(element);
  46. });
  47. return unionSet;
  48. };
  49.  
  50. // returns a new set with elements which are present in both the sets
  51. this.intersection = function (otherSet) {
  52. const intersectionSet = new MySet();
  53. const primarySet = this.values();
  54. primarySet.forEach(function (element) {
  55. if(otherSet.has(element)) {
  56. intersectionSet.add(element);
  57. }
  58. });
  59. return intersectionSet;
  60. };
  61.  
  62. // returns true if the given set is subset of other set
  63. this.subSet = function (otherSet) {
  64. const primarySet = this.values();
  65. return primarySet.every(function (element) {
  66. return otherSet.has(element);
  67. });
  68. };
  69. }
  70.  
  71. const set1 = new MySet();
  72. set1.add(10);
  73. set1.add(20);
  74. set1.add(30);
  75.  
  76. const set2 = new MySet();
  77. set2.add(10);
  78. set2.add(20);
  79. set2.add(40);
  80. set2.add(50);
  81.  
  82. const unionSet = set1.union(set2);
  83. console.log(unionSet.values());
  84.  
  85. const intersectionSet = set1.intersection(set2);
  86. console.log(intersectionSet.values());
  87.  
  88. console.log(set1.subSet(set2));
  89.  
  90. set1.remove(30);
  91. console.log(set1.subSet(set2));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement