-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeque.js
126 lines (107 loc) · 2.89 KB
/
deque.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
(function() {
var Dequeue, DequeueNode, joinBuffer;
joinBuffer = function(buf) {
var buflen, joined, pos, x, _i, _j, _len, _len2;
buflen = 0;
for (_i = 0, _len = buf.length; _i < _len; _i++) {
x = buf[_i];
buflen += x.length;
}
joined = Buffer(buflen);
pos = 0;
for (_j = 0, _len2 = buf.length; _j < _len2; _j++) {
x = buf[_j];
x.copy(joined, pos);
pos += x.length;
}
return joined;
};
exports.joinBuffer = joinBuffer;
DequeueNode = (function() {
function DequeueNode(data) {
this.data = data;
this.prev = this.next = null;
}
return DequeueNode;
})();
Dequeue = (function() {
function Dequeue() {
this.head = new DequeueNode;
this.tail = new DequeueNode;
this.empty();
}
Dequeue.prototype.empty = function() {
this.head.next = this.tail;
this.tail.prev = this.head;
return this.length = 0;
};
Dequeue.prototype.isEmpty = function() {
return this.head.next === this.tail;
};
Dequeue.prototype.push = function(data) {
var node;
node = new DequeueNode(data);
node.prev = this.tail.prev;
node.prev.next = node;
node.next = this.tail;
this.tail.prev = node;
return this.length += 1;
};
Dequeue.prototype.pop = function() {
var node;
if (this.isEmpty()) {
throw "pop() called on empty dequeue";
} else {
node = this.tail.prev;
this.tail.prev = node.prev;
node.prev.next = this.tail;
this.length -= 1;
return node.data;
}
};
Dequeue.prototype.unshift = function(data) {
var node;
node = new DequeueNode(data);
node.next = this.head.next;
node.next.prev = node;
node.prev = this.head;
this.head.next = node;
return this.length += 1;
};
Dequeue.prototype.shift = function() {
var node;
if (this.isEmpty()) {
throw "shift() called on empty dequeue";
} else {
node = this.head.next;
this.head.next = node.next;
node.next.prev = this.head;
this.length -= 1;
return node.data;
}
};
return Dequeue;
})();
Dequeue.prototype.merge_prefix = function(size) {
var chunk, joined, prefix, remaining;
if (this.length < 1) return;
if ((this.length === 1) && (this.head.next.data.length <= size)) return;
prefix = [];
remaining = size;
while (this.length && (remaining > 0)) {
chunk = this.shift();
if (chunk.length > remaining) {
this.unshift(chunk.slice(remaining));
chunk = chunk.slice(0, remaining);
}
prefix.push(chunk);
remaining -= chunk.length;
}
if (prefix) {
joined = joinBuffer(prefix);
this.unshift(joined);
}
if (this.length < 1) return this.unshift(Buffer(0));
};
exports.Dequeue = Dequeue;
}).call(this);