Last active
November 11, 2016 08:28
-
-
Save didasy/ffa388b181cea1a349c44b2230b21237 to your computer and use it in GitHub Desktop.
Ring data structrure in JavaScript.
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 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