环形数据结构

cycle.js
复制

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;

example.js
复制

const Cycle = require('./cycle')

const c = new Cycle([
  { username: 'a' },
  { username: 'b' },
  { username: 'c' },
  { username: 'd' },
  { username: 'e' }
]);

console.log(c);

console.log(c.prev);
console.log(c.current);
console.log(c.next);

c.tick();

console.info('go to next tick');

console.log(c.prev);
console.log(c.current);
console.log(c.next);

c.tick();

console.info('go to next tick');

console.log(c.prev);
console.log(c.current);
console.log(c.next);

大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!