Wednesday, October 1, 2014

[Javascript Data Structures & Algorithms] List


Here is List data structure with js.
reference is Data Structures & Algorithms with JavaScript.
In the book, there is some error and needless codes. I fix and cut off that.

function List() {
  this.listSize = 0;
  this.pos = 0;
  this.dataStore = [];
  this.clear = clear;
  this.find = find;
  this.toString = toString;
  this.insert = insert;
  this.append = append;
  this.remove = remove;
  this.contains = contains;
  this.front = front;
  this.end = end;
  this.prev = prev;
  this.next = next;
  this.length = length;
  this.currPos = currPos;
  this.moveTo = moveTo;
  this.getElement = getElement;
}

function append(element) {
  this.dataStore[this.listSize++] = element;
}

function remove(element) {
  var foundAt = this.find(element);
  if (foundAt > -1) {
    this.dataStore.splice(foundAt,1);
    --this.listSize;
    return true;
  }
  return false;
}

function find(element) {
  for(var i=0; i<this.dataStore.length; ++i) {
    if(this.dataStore[i]==element) {
      return i;
    }
  }
  return -1;
}

function length() {
  return this.listSize;
}

function toString() {
  return this.dataStore;
}

function insert(element, after) {
  var insertPost = this.find(after);
  if(insertPost > -1 ) {
    this.dataStore.splice(insertPos+1,0, element);
    ++this.listSize;
    return true;
  }
  return false;
}

function clear() {
  delete this.dataStore;
  this.dataStore.length = 0;
  this.listSize = this.pos = 0;
}

function contains(element) {
  if(this.find(element)>-1) {
    return true;
  }
  return false;
}

function front() {
  this.pos = 0;
}

function end() {
  this.pos = this.listSize-1;
}

function prev() {
  if(this.pos>=0) {
    --this.pos;
  }
}

function next() {
  if(this.pos < this.listSize) {
    ++this.pos;
  }
}

function currPos() {
  return this.pos;
}

function moveTo(position) {
  this.pos = position;
}

function getElement() {
  return this.dataStore[this.pos];
}


var names = new List();

names.append("Carrot Carrot");
names.append("Flash Maestro");
names.append("Jake Song");

for(names.front(); names.currPos() < names.length(); names.next()) {
  print(names.getElement());
}

for(names.end(); names.currPos()>=0; names.prev()) {
  print(names.getElement());
}

It is realized with Array. But in js, array and list are very similar. It's just example. If you want to realize List, Make it with C, C++, Java something like that.

My next post is List with C.

No comments:

Post a Comment