-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.rb
124 lines (106 loc) · 1.9 KB
/
queue.rb
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
# Queue
# Implementation of a classic FIFO queue using linked lists
#
# Usage:
#
# => jq = JobQueue.new
# => jq.empty?
# true
# => jq.enqueue(Proc.new {|i| puts "Job #{i}"}, [0])
# => jq.enqueue(Proc.new {|i| puts "Job #{i}"}, [1])
# => jq.count
# 2
# => jq.first
# <Job 1234: ...>
# => jq.last
# <Job 1235: ...>
# => jq.each { |j| puts j.inspect }
# <Job 1234: ...>
# <Job 1235: ...>
# => jq.last
# <Job 1235: ...>
# => job = jq.dequeue
# <Job 1234: ...>
# => job.perform
# Job 0
# => jq.count
# 1
class JobQueue
attr_accessor :first, :last
# Enqueue a new Job
# task: Proc
# args: Array
#
# Returns a new Job
def enqueue(task, args)
job = Job.new(task, args)
if empty?
self.first = job
else
last_job = self.last
last_job.next_job = job
end
self.last = job
return job
end
# Dequeue the next Job
#
# Returns the next Job to run
def dequeue
return nil if empty?
first_job = first
self.first = first_job.next_job
return first_job
end
# Is Queue empty?
#
# Returns a Boolean
def empty?
return first.nil?
end
# Count of Jobs in Queue
#
# Returns an Integer
def count
counter = 0
each do |job|
counter += 1
end
return counter
end
# Iterate over each Job
# block: Block
#
# Returns nil
def each(&block)
job = first
while job
if block
block.yield(job)
end
job = job.next_job
end
end
class Job
attr_accessor :task, :args, :next_job
# Initialize a Job
# task: Proc
# args: Array
def initialize(task, args)
self.task = task
self.args = args
end
# Perform the Job
#
# Returns nil
def perform
task.call(*args)
end
# Inspect the Job
#
# Returns a String representation of the Job
def inspect
"<Job #{object_id} task=#{task.inspect} args=#{args.inspect}>"
end
end
end