A simple implementation of the Set data structure in JavaScript. This repository demonstrates how to create a set class with essential methods and explains its functionality with practical examples.
A Set is a collection of unique elements, meaning no duplicates are allowed. It is an unordered data structure that allows efficient membership tests, additions, and deletions. Sets are often used when you need to ensure that no duplicates exist in a collection.
- Add: Add a new element to the set.
- Delete: Remove an element from the set.
- Has: Check if an element exists in the set.
- Size: Get the number of elements in the set.
- Clear: Remove all elements from the set.
Here’s the JavaScript implementation of the set:
classSet{constructor(){this.items={};// Store elements as object keys}// Add an element to the setadd(element){if(!this.has(element)){this.items[element]=element;}}// Remove an element from the setdelete(element){if(this.has(element)){deletethis.items[element];}}// Check if an element exists in the sethas(element){returnthis.items.hasOwnProperty(element);}// Get the size of the setsize(){returnObject.keys(this.items).length;}// Clear all elements from the setclear(){this.items={};}}// Initialize the setconstset=newSet();// Add elements to the setset.add(1);set.add(2);set.add(3);// Check if an element existsconsole.log(set.has(2));// Output: trueconsole.log(set.has(4));// Output: false// Get the size of the setconsole.log(set.size());// Output: 3// Remove an element from the setset.delete(2);console.log(set.has(2));// Output: false// Clear the setset.clear();console.log(set.size());// Output: 0- Removing Duplicates: Ensuring unique elements in collections such as arrays.
- Membership Testing: Efficiently checking if an element exists in a collection.
- Set Operations: Performing union, intersection, and difference between sets.
- Data Validation: Ensuring that data doesn't contain duplicates before processing.
Want to see a quick tutorial on how to build this? Check out this TikTok video:
- Clone the repository:
git clone https://github.com/fix2015/structure_set cd structure_set - Open the file
index.jsin your favorite code editor. - Run the file using Node.js:
node index.js
Contributions are welcome! If you have suggestions or want to add new features, feel free to create a pull request.
This project is licensed under the MIT License.
- LinkedIn - Vitalii Semianchuk
- Telegram - @jsmentorfree - We do a lot of free teaching on this channel! Join us to learn and grow in web development.
- Tiktok - @jsmentoring Everyday new videos
- Youtube - @jsmentor-uk Mentor live streams
- Dev.to - fix2015 Javascript featured, live, experience but about Set