Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Created July 25, 2016 06:37
Show Gist options
  • Save khaled0fares/aec945a349a48e93158c1ddea112ed06 to your computer and use it in GitHub Desktop.
Save khaled0fares/aec945a349a48e93158c1ddea112ed06 to your computer and use it in GitHub Desktop.
List data structure in JavaScript
let List = function(){
this.Store = [];
this.size = 0;
this.pos = 0;
}
List.prototype.append = function(ele){
this.Store[this.size++] = ele;
}
List.prototype.find = function(ele){
let i = 0, len = this.Store.length;
for(i; i < len; i++){
if(this.Store[i] == ele){
return i;
}
}
return -1;
}
List.prototype.remove = function(ele){
let foundAt = this.find(ele);
if(foundAt != -1){
this.Store.splice(foundAt, 1);
--this.size;
return true;
}
return false
}
List.prototype.length = function(){return this.size}
List.prototype.toString = function(){
return this.Store.join("->");
}
List.prototype.insert = function(ele, after){
var afterPos = this.find(after);
if(afterPos > -1){
this.Store.splice(afterPos+1, 0, ele);
++this.size;
return true;
}
return false;
}
List.prototype.clear = function(){
delete this.Store;
this.Store = [];
this.size = 0;
}
List.prototype.contains = function(ele){
if(this.find(ele.trim()) > -1){
return true;
}
return false;
}
List.prototype.front = function(){
this.pos = 0;
}
List.prototype.end = function(){
this.pos = this.length() - 1;
}
List.prototype.getElement = function(){
return this.Store[this.pos];
}
List.prototype.prev = function(){
if(this.pos > 0){
--this.pos
}
else{
return this.pos;
}
}
List.prototype.next = function(){
if(this.pos < this.length() - 1){
++this.pos;
}
else{
return this.pos;
}
}
List.prototype.currentPosition = function(){
return this.pos;
}
List.prototype.moveTo = function(pos){
if(pos >= 0 && pos < this.length()){
this.pos = pos;
}
}
List.prototype.incrementPosition = function(){++this.pos}
List.prototype.decrementPosition = function(){--this.pos}
List.prototype.iterateForward = function(){
for(this.front(); this.currentPosition() < this.length(); this.incrementPosition()){
console.log(this.getElement());
}
}
List.prototype.iterateBackward = function(){
for(this.end(); this.currentPosition() >= 0; this.decrementPosition()){
console.log(this.getElement());
}
}
let list = new List();
list.append("Khaled");
list.append("Fares");
list.insert("Mohammed", "Khaled");
list.iterateForward();
list.iterateBackward();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment