Last active
December 6, 2017 02:48
-
-
Save axetroy/9fca774bd739a5dc61e8aadcd11e8f76 to your computer and use it in GitHub Desktop.
环形数据结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment