Skip to content

Instantly share code, notes, and snippets.

@didasy
Last active November 11, 2016 08:28
Show Gist options
  • Save didasy/ffa388b181cea1a349c44b2230b21237 to your computer and use it in GitHub Desktop.
Save didasy/ffa388b181cea1a349c44b2230b21237 to your computer and use it in GitHub Desktop.
Ring data structrure in JavaScript.
class Ring {
constructor(...data) {
this.position = 0;
if (data instanceof Array) {
this.data = data[0];
return;
}
this.data = data;
}
value() {
return this.data[this.position];
}
toArray() {
return this.data;
}
length() {
return this.data.length;
}
index() {
return this.position;
}
next() {
let pos = this.position + 1;
if (!this.data[pos]) {
pos = 0;
}
this.position = pos;
return this;
}
prev() {
let pos = this.position - 1;
if (!this.data[pos]) {
pos = this.data.length - 1;
}
this.position = pos;
return this;
}
pop() {
this.data.splice(this.position, 1);
return this;
}
push(data) {
this.data.splice(this.position, 0, data);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment