-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsolution.js
More file actions
100 lines (86 loc) · 2.57 KB
/
solution.js
File metadata and controls
100 lines (86 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env node
function Queue() {
this.length = 0;
this.begin = 0;
this.data = new Array(1);
}
Queue.prototype.empty = function() {
return this.length == 0;
};
Queue.prototype.pushBack = function(item) {
if (this.data.length < this.length + 1) {
var new_data;// = new Array((this.length + 1) * 3 / 2);
if (this.begin == 0) {
new_data = this.data.concat(new Array(~~((this.length + 1) / 2)));
} else {
// 2 parts, wrapped
var p1begin = this.begin;
var p1len = this.data.length - p1begin;
var p2begin = 0;
var p2len = this.length - p1len;
new_data = this.data.slice(p1begin, p1begin + p1len).
concat(this.data.slice(p2begin, p2begin + p2len)).
concat(new Array(~~((this.length + 2) / 2)));
this.begin = 0;
}
this.data = new_data;
}
this.data[(this.begin + this.length) % this.data.length] = item;
this.length++;
};
Queue.prototype.popFront = function() {
var result = this.data[this.begin];
this.length--;
this.begin = (this.begin + 1) % this.data.length;
return result;
};
require("should");
describe("Queue", function() {
describe("#empty()", function() {
it("should return true when no elements have been added", function() {
var queue = new Queue();
queue.empty().should.be.true;
});
it("should return false when an element has been pushBack()ed", function() {
var queue = new Queue();
queue.pushBack(1);
queue.empty().should.be.false;
});
it("should return true when an element has been pushBack()ed and popFront()ed", function() {
var queue = new Queue();
queue.pushBack(1);
queue.popFront();
queue.empty().should.be.true;
});
});
describe("#popFront()", function() {
it("should return the items in the order they were passed to pushBack()", function() {
var queue = new Queue();
queue.pushBack(1);
queue.pushBack(2);
queue.pushBack(3);
queue.popFront().should.equal(1);
queue.popFront().should.equal(2);
queue.popFront().should.equal(3);
queue.empty().should.be.true;
queue.pushBack(4);
queue.empty().should.be.false;
queue.popFront().should.equal(4);
queue.empty().should.be.true;
var inval = 0;
var out = 0;
for (var i = 1; i < 100; i++) {
for (var j = 0; j < i; j++) {
queue.pushBack(inval);
inval++;
}
queue.popFront().should.equal(out);
out++;
}
while (!queue.empty()) {
queue.popFront().should.equal(out);
out++;
}
});
});
});