From f8e1a6cac30a1467a518e2a5a74fee376e38f995 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:59:33 +1000 Subject: [PATCH] Data Structures: Perform a Union on Two Sets --- Data Structures/setsUnion.js | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Data Structures/setsUnion.js diff --git a/Data Structures/setsUnion.js b/Data Structures/setsUnion.js new file mode 100644 index 0000000..c4a6686 --- /dev/null +++ b/Data Structures/setsUnion.js @@ -0,0 +1,62 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/perform-a-union-on-two-sets + +class Set { + constructor() { + // This will hold the set + this.dictionary = {}; + this.length = 0; + } + // This method will check for the presence of an element and return true or false + has(element) { + return this.dictionary[element] !== undefined; + } + // This method will return all the values in the set + values() { + return Object.values(this.dictionary); + } + // This method will add an element to the set + add(element) { + if (!this.has(element)) { + this.dictionary[element] = element; + this.length++; + return true; + } + + return false; + } + // This method will remove an element from a set + remove(element) { + if (this.has(element)) { + delete this.dictionary[element]; + this.length--; + return true; + } + + return false; + } + // This method will return the size of the set + size() { + return this.length; + } + // Only change code below this line + union(otherSet) { + const unionSet = new Set(); + for (let set of [this, otherSet]) { + for (let key in set.dictionary) { + unionSet.add(key); + } + } + return unionSet; + } + // Only change code above this line +} + +const setA = new Set(); +for (let element of ["a", "b", "c"]) { + setA.add(element); +} +const setB = new Set(); +setB.add("c"); +setB.add("d"); + +console.log(setA.union(setB));