Javascript Set data structure

bvnkumar

Bvnkumar

Posted on April 17, 2022

Javascript Set data structure

Set: Set data structure allow to add data to a container.

This custom Set implementation in JavaScript uses an array (collection[]) to store unique values, similar to the built-in Set object. It provides methods to add, remove, check, and retrieve the size of the collection while ensuring each element is unique.

Methods:

  • size(): Returns the number of elements in the set.
  • has(item): Checks if the set contains a specific item.
  • add(item): Adds a new item to the set if it doesn’t already exist.
  • delete(item): Removes an item from the set if it exists.
  • clear(): Removes all items from the set.
  • values(): Returns all the items in the set.

Here is an example of set internal implementation.

const Set=function(){
  let collection=[];
  this.size=function(){
    return collection.length;
  }
  this.has=function(item){
   return collection.indexOf(item)!==-1
  }
  this.add=function(item){
    if(!this.has(item)){
      collection.push(item)
      return true;
    }
    return false;
  }
  this.delete=function(item){
    if(!this.has(item)){
      return false;
    }else{
      let index=collection.indexOf(item);
      collection.splice(index,1);
      return true;
    }
  }
  this.clear=function(){
    collection=[];
  }
  this.values=function(){
    return collection;
  }
}
let set=new Set();
console.log(set.size());
console.log(set.add(1));
console.log(set.add(2));
console.log(set.size());
console.log(set.delete(2));
console.log(set.delete(2));
console.log(set.size());
Enter fullscreen mode Exit fullscreen mode

Time Complexity:

  • size(): O(1) - Simply returns the length of the array.
  • has(item): O(n) - The indexOf() method is used, which performs a linear search through the array.
  • add(item): O(n) - Before adding, it calls has(item) which is O(n), and if the item doesn’t exist, push() is O(1).
  • delete(item): O(n) - It uses indexOf() to find the index of the item, which is O(n), and then splice() to remove it, which is also O(n).
  • clear(): O(1) - Just resets the array to an empty array.
  • values(): O(1) - Returns the reference to the array. > Any comments or suggestions are welcome.
💖 💪 🙅 🚩
bvnkumar
Bvnkumar

Posted on April 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Javascript Set data structure
javascript Javascript Set data structure

April 17, 2022