class Node {
constructor(prev, value, next) {
this.prev = prev;
this.next = next;
this.value = value;
}
}
const CURRENT_INDEX = Symbol('current index in cycle');
const ROUND_INDEX = Symbol('how many round in cycle');
const MAP_KEY = Symbol('map in cycle');
class Cycle {
constructor(nodes) {
this[CURRENT_INDEX] = 0;
this[ROUND_INDEX] = 0;
this[MAP_KEY] = new Map();
Object.defineProperty(this, 'length', {
enumerable: false,
configurable: false,
value: nodes.length
});
for (let i = 0; i < this.length; i++) {
let node;
if (i === 0) {
node = new Node(
nodes[this.length - 1],
nodes[i],
nodes[Math.min(this.length - 1, i + 1)]
);
} else if (i === this.length - 1) {
node = new Node(nodes[i - 1], nodes[i], nodes[0]);
} else {
node = new Node(nodes[i - 1], nodes[i], nodes[i + 1]);
}
this[MAP_KEY].set(i, node);
}
}
get current() {
return this[MAP_KEY].get(this[CURRENT_INDEX]).value;
}
get prev() {
return this[MAP_KEY].get(this[CURRENT_INDEX]).prev;
}
get next() {
return this[MAP_KEY].get(this[CURRENT_INDEX]).next;
}
tick() {
let nextIndex = this[CURRENT_INDEX] + 1;
if (nextIndex >= this.length) {
nextIndex = 0;
this[ROUND_INDEX]++;
}
this[CURRENT_INDEX] = nextIndex;
}
}
module.exports = Cycle;
大牛们的评论:朕有话说
还没有人评论哦,赶紧抢沙发!