背景
通过JavaScript实现了一种类似栈或链表的结构,可用于面包屑导航、操作记录缓存等场景,实现了增加、移除、长度返回、数据返回、跳转等操作。
代码
var StackHelper = function () {
this.head = null;
this.tail = null;
// 可通过datas遍历元素
this.datas = [];
// stackItem = {pre:o, next:o, data:obj}
/**
* pop() 移除栈顶元素(不会返回栈顶元素的值)
push(obj) 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素
jump(index) 跳转到从底部开始的某个索引,即抛弃栈顶部的一些元素。
* */
// 在栈顶增加元素
/*
在栈顶增加元素
*/
this.push = function (obj) {
var stackItem = {
pre: this.datas.length > 0 ? this.datas[this.datas.length - 1] : null,
next: null,
data: obj
};
this.datas.length > 0 ? this.datas[this.datas.length - 1].next = stackItem : this.head = stackItem;
this.tail = stackItem;
this.datas.push(stackItem);
}
this.pop = function () {
if (this.datas.length > 0) {
delete this.datas[this.datas.length - 1];
if (this.datas.length > 0) {
this.datas[this.datas.length - 1].next = null;
this.tail = this.datas[this.datas.length - 1];
} else {
this.head = null;
this.tail = null;
}
}
}
this.size = function () {
return this.datas.length;
}
this.top = function () {
return this.tail;
}
this.jump = function (index) {
if (index >= this.datas.length) {
return;
}
var _ds = [];
for (var i = 0; i <= index; i++) {
_ds.push(this.datas[i]);
}
this.datas = _ds;
this.datas[this.datas.length - 1].next = null;
this.tail = this.datas[this.datas.length - 1];
}
return this;
}