DEV Community

Bvnkumar
Bvnkumar

Posted on • Updated on

Javascript Set data structure

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

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

Any comments or suggestions are welcome.

Top comments (0)