Ivankooo1

List

Aug 30th, 2020
1,773
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class List{
  2.  
  3.   constructor(){
  4.       this._list = [];
  5.       this.size = 0;
  6.   }
  7.  
  8.   add(element){
  9.       this._list.push(element);
  10.       this._list.sort((a,b)=>a-b);
  11.       this.size++;
  12.   }
  13.  
  14.   remove(index){
  15.      this._validate(index)
  16.      this._list.splice(index,1);
  17.      this.size--;
  18.   }
  19.  
  20.   get(index){
  21.      this._validate(index);
  22.      return this._list[index];
  23.   }
  24.  
  25.   _validate(index){
  26.     if(index < 0 || index >= this._list.length){
  27.       throw new Error('Index is out of bounds')
  28.     }
  29.   }
  30.  
  31. }
  32.  
  33. let list = new List();
  34. list.add(5);
  35. list.add(6);
  36. list.add(7);
  37. console.log(list.get(1));
  38. list.remove(1);
  39. console.log(list.get(1));
  40. console.log(list.size)
  41.  
Advertisement
Add Comment
Please, Sign In to add comment