On 11/10/06, Ruby Quiz <james / grayproductions.net> wrote:
> Your task is to provide an implementation for the ProgramManager.
>
> You can see the unit tests I used at:
>         http://www.rubyquiz.com/program_manager_test.rb

I started from the first test class here, and progressively re-enabled
the test cases to make them pass as I went along.  This class passes
all tests.

Rule of the day was the simplest thing that could possibly work.  As
such, I didn't feel the need to split the logic out into a separate
Program class, but I kept two arrays of prospective programs - one for
recurring and one for one-shot.

- Jamie


class ProgramManager
  DAYS = %w(sun mon tue wed thu fri sat)

  def initialize
    @recurring = Hash.new{|h,k| h[k] = []}
    @concrete = []
  end

  def add(o)
    case o[:start]
    when Fixnum:
      o[:days].each do |day|
        @recurring[DAYS.index(day)] << [o[:start]..o[:end], o[:channel]]
      end
    when Time:
      @concrete.unshift [o[:start]..o[:end], o[:channel]]
    end
  end

  def record?(time)
    @concrete.each do |times, channel|
      return channel if times.include? time
    end

    time_s = (time.hour*60 + time.min)*60 + time.sec
    @recurring.each do |day, programs|
      next unless day == time.wday
      programs.each do |times, channel|
        return channel if times.include? time_s
      end
    end
    nil
  end
end