js用陣列實現List
阿新 • • 發佈:2019-01-04
"use strict";
function List() {
this.dataStore = [];
this.pos = 0; // note
this.listSize = 0;
this.length = length;
this.clear = clear;
this.pos = pos;
this.append = append;
this.insert = insert;
this.remove = remove;
this.getElement = getElement;
this.front = front;
this .end = end;
this.prev = prev;
this.next = next;
this.moveTo = moveTo;
this.find = find;
this.toString = toString;
this.curPos = curPos;
this.contains = contains;
}
function append(element) {
this.dataStore[listSize++] = element;
}
function remove(element) {
var pos = this .find(element);
if (pos > -1) {
this.dataStore.splice(pos, 1);
}
}
function find(element) {
for (let i = 0; i < listSize; i++) {
if (this.dataStore[i] === element) {
return i;
}
}
return -1;
}
function length() {
return this.dataStore.length;
}
function toString() {
this.dataStore.toString();
// this.dataStore.join(",");
}
// method 1
// function insert(element, index) {
// if (index === 0) {
// this.dataStore.unshift(element);
// }
// this.dataStore.splice(index - 1, 0, element); // notice the second parameter
// this.listSize++;
// }
function insert(element, after) {
let insertPos = this.find(after);
if (insertPos > -1) {
this.dataStore.splice(insertPos+1, 0, element);
this.listSize++;
return true;
}
return false;
}
// notice
function clear() {
delete this.dataStore;
this.dataStore = [];
this.listSize = this.pos = 0; // reset
}
function container(element) {
for (let i = 0; i < this.dataStore.length; i++) {
if (dataStore[i] === element) {
return true;
}
}
return false;
}
// tranverse
function front() {
this.pos = 0;
}
function end() {
this.pos = listSize - 1;
}
function prev() {
if (this.pos > 0) {
this.pos -= 1;
}
}
function next() {
if (this.pos < this.listSize - 1) {
this.pos += 1;
}
}
function curPos() {
return this.pos;
}
function moveTo(position) {
this.pos = position;
}
function getElement() {
return this.dataStore[pos];
}