-
Notifications
You must be signed in to change notification settings - Fork 2
/
deque.coffee
89 lines (75 loc) · 2.02 KB
/
deque.coffee
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
joinBuffer = (buf) ->
buflen = 0; (buflen += x.length for x in buf);
joined = Buffer(buflen)
pos = 0
for x in buf
x.copy(joined, pos)
pos += x.length
return joined
exports.joinBuffer = joinBuffer
class DequeueNode
constructor: (@data) ->
@prev = @next = null
class Dequeue
constructor: ->
@head = new DequeueNode
@tail = new DequeueNode
@empty()
empty: ->
@head.next = @tail
@tail.prev = @head
@length = 0
isEmpty: ->
return @head.next == @tail
push: (data) ->
node = new DequeueNode(data)
node.prev = @tail.prev
node.prev.next = node
node.next = @tail
@tail.prev = node
@length += 1
pop: ->
if @isEmpty()
throw "pop() called on empty dequeue"
else
node = @tail.prev
@tail.prev = node.prev
node.prev.next = @tail
@length -= 1
return node.data
unshift: (data) ->
node = new DequeueNode(data)
node.next = @head.next
node.next.prev = node
node.prev = @head
@head.next = node
@length += 1
shift: ->
if @isEmpty()
throw "shift() called on empty dequeue"
else
node = @head.next
@head.next = node.next
node.next.prev = @head
@length -= 1
return node.data
Dequeue::merge_prefix = (size) ->
if @length < 1
return
if (@length == 1) and (@head.next.data.length <= size)
return
prefix = []
remaining = size
while (@length) and (remaining > 0)
chunk = @shift()
if (chunk.length > remaining)
@unshift( chunk.slice(remaining) )
chunk = chunk.slice(0, remaining)
prefix.push(chunk)
remaining -= chunk.length
if prefix
joined = joinBuffer(prefix)
@unshift(joined)
if @length < 1
@unshift( Buffer(0) )
exports.Dequeue = Dequeue