Skip to content

Instantly share code, notes, and snippets.

@easonhan007
Created September 1, 2014 08:21
Show Gist options
  • Save easonhan007/a94ea5e1e4d50612ae61 to your computer and use it in GitHub Desktop.
Save easonhan007/a94ea5e1e4d50612ae61 to your computer and use it in GitHub Desktop.
How to implement list data structure using javascript
function List() {
this.listSize = 0;
this.pos = 0;
this.dataSource = [];
this.clear = clear;
this.find = find;
this.toString = toString;
this.insert = insert;
this.append = append;
this.remove = remove;
this.front = front;
this.end = end;
this.prev = prev;
this.next = next;
this.length = length;
this.currPos = currPos;
this.moveTo = moveTo;
this.getElement = getElement;
this.contains = contains;
function append(element) {
this.dataSource[this.listSize++] = element;
}
function find(element) {
for(var i = 0; i < this.dataSource.length; ++i) {
if(this.dataSource[i] == element) return i;
}
return -1;
} //find
function remove(element) {
var findAt = this.find(element);
if (findAt > -1) {
this.dataSource.splice(findAt, 1);
--this.listSize;
return true;
}
return false;
}
function length() {
return this.listSize;
}
function toString() {
return this.dataSource;
}
function insert(element, after) {
var insertPos = this.find(after);
if(insertPos > -1) {
this.dataSource.splice(insertPos, 0, element);
++this.listSize;
return true;
}
return false;
} //insert
function clear() {
delete this.dataSource;
this.dataSource = [];
this.listSize = this.pos = 0;
}
function contains(element) {
for(var i = 0; i < this.dataSource.length; ++i) {
if(this.dataSource[i] == element) return true;
}
return false;
} //contains
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-1) ++this.pos;
}
function currPos() {
return this.pos;
}
function moveTo(position) {
this.pos = position;
}
function getElement() {
return this.dataSource[this.pos];
}
}
var names = new List();
names.append('ada');
names.append('bob');
names.append('clark');
// console.log(names.toString());
// names.front();
// console.log(names.getElement());
// names.next();
// console.log(names.getElement());
// interate a list
console.log(names.length());
for(names.front(); names.currPos() < names.length(); names.next()) {
console.log(names.getElement());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment