Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active September 18, 2016 09:45
Show Gist options
  • Save gaogao-9/9d511d7fa7156a9a3bc537bc32e1006f to your computer and use it in GitHub Desktop.
Save gaogao-9/9d511d7fa7156a9a3bc537bc32e1006f to your computer and use it in GitHub Desktop.
import Circle from "Util/Circle"
const circleMap = new WeakMap();
export default class SelectableArray extends Array{
static get [Symbol.species]() { return SelectableArray; }
constructor(...args){
super(...args);
}
random(){
return this[Math.random()*this.length|0];
}
sequence(){
let circle = circleMap.get(this);
if(circle){
circle.length = this.length;
}
else{
circle = new Circle(this.length);
}
const value = this[circle.now];
circle.succ;
circleMap.set(this, circle);
return value;
}
}
class Circle{
constructor(length, offset=0){
this._offset = offset;
this.now = this._offset;
this.length = length;
}
set now(value){
this._cursor = value;
this.succ; this.prev;
}
get now(){
return this._cursor;
}
set length(value){
this._length = value - 1;
this.succ; this.prev;
}
get length(){
return this._length + 1;
}
get succ(){
this._cursor++;
if(this._cursor > (this._length+this._offset)) this._cursor = this._offset;
return this._cursor;
}
get prev(){
this._cursor--;
if(this._cursor < this._offset) this._cursor = (this._length+this._offset);
return this._cursor;
}
}
export default Circle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment