dev-resources.site
for different kinds of informations.
Javascript Set data structure
Published at
4/17/2022
Categories
javascript
set
datastructure
programming
Author
Bvnkumar
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());
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.
Articles
12 articles in total
LRU (Least Recently Used) Cache Data Structure
read article
Observer Design Pattern using Javascript
read article
Javascript Factory Design Pattern
read article
Longest string without repeating characters in javaascript
read article
Print left view of binary tree
read article
Binary search algorithm implementation in JavaScript
read article
Javascript Binary heap data structure
read article
Javascript Linked List data structure
read article
Javascript Binary Tree data structure
read article
Javascript Queue data structure
read article
Javascript Set data structure
currently reading
Javascript Stack Data Structure.
read article
Featured ones: