Add comments to Timeline
[god.git] / lib / god / timeline.rb
blob7ad12a640cad253c1fdd9f897be64160e27086a7
1 module God
2   
3   class Timeline < Array
4     # Instantiate a new Timeline
5     #   +max_size+ is the maximum size to which the timeline should grow
6     #
7     # Returns Timeline
8     def initialize(max_size)
9       super()
10       @max_size = max_size
11     end
12     
13     # Push a value onto the Timeline
14     #   +val+ is the value to push
15     # 
16     # Implementation explanation:
17     # A performance optimization appears here to speed up the push time.
18     # In essence, the code does this:
19     #
20     #   def push(val)
21     #     super(val)
22     #     shift if size > @max_size
23     #   end
24     #
25     # But that's super slow due to the shift, so we resort to reverse! and pop
26     # which gives us a 2x speedup with 100 elements and a 6x speedup with 1000
27     #
28     # Returns Timeline
29     def push(val)
30       if (size + 1) > @max_size
31         reverse!
32         pop
33         reverse!
34       end
35       super(val)
36     end
37     
38     # Push a value onto the timeline
39     #   +val+ is the value to push
40     #
41     # Returns Timeline
42     def <<(val)
43       push(val)
44     end
45   end
46   
47 end