How to implement lists in Javascript?


Want to implement lists in javascript? if yes, you are in the right path. Traditional programming languages like C,C++ and Java provides a standard implementation of data structures, but Javascript doesn’t have a standard way to do that.

To understand data structures in traditional languages is a bit harder but in my opinion Implementing and Understanding data structures in Javascript is easier, compare to other languages.

In this tutorial I am going to Implement lists in Javascript using javascript new class feature.

Lists in Javascript

This tutorial you need two files index.html and script.js. There is nothing to do with index.html. we just link the js file to make it available at chrome console.

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <script src="script.js" charset="utf-8"></script>
</head>
<body>

</body>
</html>

script.js

I started with creating a list class with a constructor.

class List{
 constructor(){
 
  this.items = [];
  this.currentPosition = 0;

 }

}

this.items array holds all the list items. this.currentPosition  holds the  position of current list item.

The following methods to be implemented to full fill the function of a List

1. add –  method to add items to list

add(item){
  this.items.push(item);
}

2. show – method to display all the items of a list

show(){
    if(this.items.length === 0){
        console.log("List was empty");
    }else{
        this.items.forEach(function(elm){
          console.log(elm)
        });
    }     
}

The above code first check’s the length of items array, if the length of items array is not equal to 0, then it loops over the items array and prints every element in item’s array.

3. size – method to display’s the size of the list.

size(){
     console.log(this.items.length);
}

it simply log’s the length of the items array.

4. remove – method to remove a particular element from a list

remove(item){
  this.items.forEach((elm,key)=>{
    if(this.items[key] === item){
      this.items.splice(key,1);
    }
  });
}

The above method first loop over the  item’s array, then it checks for the index, if the index match with the passed value, it will remove the element using splice method.

5. first – this method will take you to the first item of a list.

first(){
  this.currentPosition=0;
}

the above method will set the this.currentPosition to 0.

6. last – this method will take you to the last item of a list.

last(){
  this.currentPosition=this.items.length-1;
}

the above method will set the currentPosition to list length minus 1

7. find – this method will find’s the item in a list.

find(item){	
  var itemIndex=this.items.indexOf(item);
  if(itemIndex === -1){
    console.log("Not Found");
  }else{
    console.log("Item Founded");
  }	
}

The method first find’s the index of passed value using indexOf method. If the index not equals to -1, it will log “Item Founded”

8. insert –   this method will insert an item into a list at particular position.

insert(item,position){
  let items=this.items;
  items.forEach((elm,key)=>{
    if(items[key] === position){
      items[key+1]=item;
    }
  });
  this.items=items;		
}

The method will accept two arguments item and after. item is the list item which is to be inserted and position is the position of existing item. The method first loop over the items array and check’s every element index with position. If after matched with any of list item’s index, then the item should be placed  immeaditely after position. 

9. clear – this method will remove all the item’s of a list.

clear(){
  this.items=[];
}

the method simply empty the items array.

10. prev –  this method will take you to the previous item.

prev(){
  if(this.currentPosition === 0){
    this.currentPosition=this.items.length-1;
    console.log(this.items[this.currentPosition]);
  }else{
    console.log(this.items[this.currentPosition]);
  }
  return this.currentPosition--;
}

The above method will decrement the value of currentPosition and log’s the value. If the currentPosition is 0 logs the last element of a list.

11. next – this method will traverse to the next item of a list

next(){
  return this.currentPosition++;
}

The above method will increment the value of currentPosition.

12. current – display’s the current item of a list.

current(){
  console.log(this.items[this.currentPosition]);
}

The above method will log the items array using currentPosition.

Ok! now the implementation of list data structure is complete.

Let’s create a list

var list=new List();

It seems like a simple object but it has a lot of functions which we just build.

If you put everything together your script.js file should look like this.

script.js

//creating class List
class List{

  //initializing consturctor method
  constructor(){
    
    this.items=[];

    //creting varible for holding current position of a list
    this.currentPosition=0;
  }

  //method to add a element to list.
  add(item){
    this.items.push(item);
  }

  //method to displaying all the elements of a list
  show(){
    if(this.items.length === 0){
      console.log("List was empty");
    }else{
      this.items.forEach(function(elm){
        console.log(elm)
      });
    }

  }

  //method to display the size of a list
  size(){
    console.log(this.items.length);
  }

  //method to remove a particular element from a list
  remove(item){
    this.items.forEach((elm,key)=>{
      if(this.items[key] === item){
        this.items.splice(key,1);
      }
    });
  }

  //prints the first element of a list
  first(){
    this.currentPosition=0;
  }

  //prints the last element of a list
  last(){
    this.currentPosition=this.items.length-1;
  }

  //finding an item
  find(item){
    var itemIndex=this.items.indexOf(item);
    if(itemIndex === -1){
      console.log("Not Found");
    }else{
      console.log("Founded");
    }
  }

  //inserting an item into a list at particular position
  insert(item,position){
    let items=this.items;
    items.forEach((elm,key)=>{
      if(items[key] === position){
        items[key+1]=item;
      }
    });
    this.items=items;
  }

  //removing all the items of list
  clear(){
    this.items=[];
  }

  //traverse list to previous item.
  prev(){
    if(this.currentPosition === 0){
      this.currentPosition=this.items.length-1;
      console.log(this.items[this.currentPosition]);
    }else{
      console.log(this.items[this.currentPosition]);
    }
    return this.currentPosition--;
  }

  //traverse list to next item
  next(){
    console.log(this.items[this.currentPosition]);
    return this.currentPosition++;
  }

  //display the current item
  current(){
    console.log(this.items[this.currentPosition]);
  }
}

var list=new List();

list.show();

Below are the sample screenshot of chrome console while working with javascript lists.

implementing lists in javascript

I hope, now you understand how to implement lists in javascript. If you like this tutorial, share with your friends.

also read  what is the difference between website and blog?


Leave a Reply

Your email address will not be published. Required fields are marked *