Skip to content

Commit

Permalink
Fixing CircularBuffer.unshift
Browse files Browse the repository at this point in the history
  • Loading branch information
Yomguithereal committed Jan 25, 2019
1 parent fbb5240 commit 2e88774
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
12 changes: 9 additions & 3 deletions circular-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,21 @@ CircularBuffer.prototype.push = function(item) {
* @return {number} - Returns the new size of the buffer.
*/
CircularBuffer.prototype.unshift = function(item) {
if (this.size === this.capacity)
throw new Error('mnemonist/circular-buffer.unshift: buffer capacity (' + this.capacity + ') exceeded!');

var index = this.start - 1;

if (this.start === 0)
index = this.capacity - 1;

this.items[index] = item;

// Overwriting
if (this.size === this.capacity) {

this.start = index;

return this.size;
}

this.start = index;

return ++this.size;
Expand Down
30 changes: 29 additions & 1 deletion test/circular-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('CircularBuffer', function() {
assert.strictEqual(buffer.capacity, 10);
});

it('should be possible to wrap buffer around.', function() {
it('should be possible to wrap buffer around when pushing.', function() {
var buffer = new CircularBuffer(Array, 3);

buffer.push(1);
Expand Down Expand Up @@ -63,6 +63,34 @@ describe('CircularBuffer', function() {
assert.strictEqual(buffer.size, 3);
});

it('should be possible to wrap buffer around when unshifting.', function() {
var buffer = new CircularBuffer(Array, 3);

buffer.unshift(1);
buffer.unshift(2);
buffer.unshift(3);
buffer.unshift(4);

assert.deepEqual(buffer.toArray(), [4, 3, 2]);
assert.strictEqual(buffer.size, 3);

buffer.unshift(5);

assert.deepEqual(buffer.toArray(), [5, 4, 3]);
assert.strictEqual(buffer.size, 3);

buffer.unshift(6);

assert.deepEqual(buffer.toArray(), [6, 5, 4]);
assert.strictEqual(buffer.size, 3);

buffer.unshift(7);
buffer.unshift(8);

assert.deepEqual(buffer.toArray(), [8, 7, 6]);
assert.strictEqual(buffer.size, 3);
});

it('should be possible to clear the buffer.', function() {
var buffer = new CircularBuffer(Array, 2);

Expand Down
4 changes: 4 additions & 0 deletions test/fixed-deque.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ describe('FixedDeque', function() {
assert.throws(function() {
deque.push('test');
}, /exceed/);

assert.throws(function() {
deque.unshift('test');
}, /exceed/);
});

it('should be possible to clear the deque.', function() {
Expand Down

0 comments on commit 2e88774

Please sign in to comment.