Skip to content

Instantly share code, notes, and snippets.

@mriddle
Last active March 29, 2019 21:35
Show Gist options
  • Save mriddle/2df19095f6bb35ab514e8efeb7035005 to your computer and use it in GitHub Desktop.
Save mriddle/2df19095f6bb35ab514e8efeb7035005 to your computer and use it in GitHub Desktop.
module Helpers
class Range
def self.merge_overlapping_ranges(ranges)
ranges.sort_by(&:begin).inject([]) do |collection, range|
if !collection.empty? && overlap?(collection.last, range)
collection[0...-1] + [merge(collection.last, range)]
else
collection + [range]
end
end
end
def self.overlap?(range_1, range_2)
range_1.include?(range_2.begin) || range_2.include?(range_1.begin)
end
def self.merge(range_1, range_2)
[range_1.begin, range_2.begin].min..[range_1.end, range_2.end].max
end
end
end
class LightHub
def initialize
@time_periods = []
end
def record_runtime(range)
@time_periods << range
end
def reset!
@time_periods = []
end
def total_runtime
ranges = Helpers::Range.merge_overlapping_ranges(@time_periods)
ranges
.inject([]) { |diff, range| diff << range.max - range.min }
.sum
end
end
class Assertions
CHECKMARK = "\xE2\x9C\x94"
CROSS = "\xE2\x9D\x8C"
COLOURS = {
green: "\033[0;32m",
red: "\033[0;31m"
}
def self.assert_equal(expected, actual)
result = expected == actual
line_number = caller_locations[0].lineno
if result
puts "#{COLOURS[:green]}#{CHECKMARK} #{line_number}: Passed"
else
puts "#{COLOURS[:red]}#{CROSS} #{line_number}: Assertion Failed. \n\tExpected: #{expected} \n\tActual: #{actual}"
exit(1)
end
end
end
light_hub = LightHub.new
light_hub.record_runtime(1..3)
Assertions.assert_equal(2, light_hub.total_runtime)
light_hub.record_runtime(2..3)
Assertions.assert_equal(2, light_hub.total_runtime)
light_hub.record_runtime(4..5)
Assertions.assert_equal(3, light_hub.total_runtime)
light_hub.record_runtime(2..8)
Assertions.assert_equal(7, light_hub.total_runtime)
light_hub.record_runtime(1..3)
Assertions.assert_equal(7, light_hub.total_runtime)
light_hub.reset!
Assertions.assert_equal(0, light_hub.total_runtime)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment