Class: TimeSlotCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/slotter/time_slot_collection.rb

Overview

A TimeSlotCollection object holds a collection of TimeSlot objects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time_slots = []) ⇒ TimeSlotCollection

Returns a new collection of time slots where the default is empty.



6
7
8
# File 'lib/slotter/time_slot_collection.rb', line 6

def initialize(time_slots = [])
  @time_slots = Array.new(time_slots)
end

Instance Attribute Details

#time_slotsObject (readonly)

Returns the value of attribute time_slots.



3
4
5
# File 'lib/slotter/time_slot_collection.rb', line 3

def time_slots
  @time_slots
end

Instance Method Details

#<<(slot) ⇒ Object

Append—Pushes slot to the end of the internal collection of time_slots if slot is not already a part of it. This expression returns self, so several appends may be chained together.



13
14
15
16
# File 'lib/slotter/time_slot_collection.rb', line 13

def <<(slot)
  @time_slots << slot unless @time_slots.include?(slot)
  return self
end

#compressObject

Returns a copy of self where all intersecting slots have been joined.

x = [09:00 to 13:00, 12:00 to 14:00]

x.compress #=> [09:00 to 14:00]



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/slotter/time_slot_collection.rb', line 35

def compress
  result = TimeSlotCollection.new
  for slot_a in @time_slots
    current_slot = slot_a
    for slot_b in @time_slots
      current_slot += slot_b unless current_slot.disjoint?(slot_b)
    end
    result << current_slot
  end
  return result
end

#compress!Object

Joins all intersecting slots in time_slots. Returns nil if no changes where made.



49
50
51
52
# File 'lib/slotter/time_slot_collection.rb', line 49

def compress!
  result = self.compress.time_slots
  (result == @time_slots)? nil : self
end

#each(&block) ⇒ Object

Calls block once for each element in self.time_slots, passing that element as a parameter.



62
63
64
65
66
# File 'lib/slotter/time_slot_collection.rb', line 62

def each(&block)
  for slot in time_slots
    yield(slot)
  end
end

#merge(other_collection) ⇒ Object Also known as: +

Creates a new collection that contains the compressed union of self.time_slots and other_collection.time_slots.



56
57
58
# File 'lib/slotter/time_slot_collection.rb', line 56

def merge(other_collection)
  self.union(other_collection).compress
end

#to_sObject

Returns self.time_slots.to_s



71
72
73
# File 'lib/slotter/time_slot_collection.rb', line 71

def to_s
  "#{@time_slots}"
end

#union(other_collection) ⇒ Object

Returns a new collection that contains all slots from self and other_collection.



20
21
22
23
24
25
26
# File 'lib/slotter/time_slot_collection.rb', line 20

def union(other_collection)
  result = self.clone
  for slot in other_collection.time_slots
    result << slot
  end
  return result
end