Skip to content

Commit 6b486f5

Browse files
committed
fix a few edge cases in queue.pop()
1 parent 559ca27 commit 6b486f5

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

index.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,14 @@ TinyQueue.prototype = {
2727
},
2828

2929
pop: function () {
30+
if (this.length === 0) return undefined;
3031
var top = this.data[0];
31-
this.data[0] = this.data[this.length - 1];
3232
this.length--;
33+
if (this.length > 0) {
34+
this.data[0] = this.data[this.length];
35+
this._down(0);
36+
}
3337
this.data.pop();
34-
this._down(0);
3538
return top;
3639
},
3740

test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,20 @@ test('accepts data in constructor', function (t) {
3636

3737
t.end();
3838
});
39+
40+
test('handles edge cases with few elements', function (t) {
41+
var queue = tinyQueue();
42+
43+
queue.push(2);
44+
queue.push(1);
45+
queue.pop();
46+
queue.pop();
47+
queue.pop();
48+
queue.push(2);
49+
queue.push(1);
50+
t.equal(queue.pop(), 1);
51+
t.equal(queue.pop(), 2);
52+
t.equal(queue.pop(), undefined);
53+
54+
t.end();
55+
});

0 commit comments

Comments
 (0)