Skip to content

Commit

Permalink
Count rings as they are added / removed to make .capacity O(1)
Browse files Browse the repository at this point in the history
  • Loading branch information
erayd committed Sep 8, 2016
1 parent d6237c7 commit a8028f2
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Spique - A Spiral Double-Ended Queue

Spique is a deque implemented as a doubly-linked list of circular buffers. This
structure allows for both high performance and unlimited dynamic growth of the
queue. All operations are O(1) except the `.capacity` property, which is O(n).
queue. All operations are O(1) (constant time).

Spique does not require an initial or maximum size (although you can define a
maximum if you wish), and will both grow and shrink dynamically as items are
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "spique",
"version": "1.0.4",
"version": "1.0.5",
"description": "A spiral deque - high performance and dynamic queue size",
"main": "spique.js",
"scripts": {
Expand Down
10 changes: 6 additions & 4 deletions spique.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ function Spique(maxItems, circumference) {

var firstRing = new RingBuffer(circumference);
var lastRing = firstRing;
var rings = 1;
var items = 0;

// check whether the buffer is empty
Expand All @@ -41,6 +42,7 @@ function Spique(maxItems, circumference) {
lastRing.nextRing = newRing;
newRing.prevRing = lastRing;
lastRing = newRing;
rings++;
}
lastRing.push(value);
items++;
Expand All @@ -58,6 +60,7 @@ function Spique(maxItems, circumference) {
newRing.nextRing = firstRing;
firstRing.prevRing = newRing;
firstRing = newRing;
rings++;
}
firstRing.unshift(value);
items++;
Expand All @@ -71,6 +74,7 @@ function Spique(maxItems, circumference) {
if(lastRing.isEmpty() && lastRing.prevRing) {
lastRing = lastRing.prevRing;
delete lastRing.nextRing;
rings--;
}
items--;
return value;
Expand All @@ -83,6 +87,7 @@ function Spique(maxItems, circumference) {
if(firstRing.isEmpty() && firstRing.nextRing) {
firstRing = firstRing.nextRing;
delete firstRing.prevRing;
rings--;
}
items--;
return value;
Expand Down Expand Up @@ -111,10 +116,7 @@ function Spique(maxItems, circumference) {

// get the current capacity
Object.defineProperty(this, 'capacity', {get: function() {
var capacity = 0;
for(var r = firstRing; r; r = r.nextRing)
capacity += circumference;
return capacity;
return rings * circumference;
}});

// get the max number of items
Expand Down

0 comments on commit a8028f2

Please sign in to comment.