Last active
January 22, 2016 20:30
-
-
Save werdlerk/adc8218a01fccc4895fa to your computer and use it in GitHub Desktop.
Launch School challenge: Circular Buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CircularBuffer | |
class BufferEmptyException < RuntimeError; end | |
class BufferFullException < RuntimeError; end | |
def initialize(size) | |
@size = size | |
@buffer = Array.new | |
end | |
def write(value) | |
return if value.nil? | |
@buffer.push(value) unless exception_on_full | |
end | |
def write!(value) | |
return if value.nil? | |
@buffer.shift if full? | |
write(value) | |
end | |
def read | |
@buffer.shift unless exception_on_empty | |
end | |
def clear | |
@buffer.clear | |
end | |
private | |
def full? | |
@buffer.size >= @size | |
end | |
def exception_on_full | |
raise BufferFullException.new if full? | |
end | |
def empty? | |
@buffer.size == 0 | |
end | |
def exception_on_empty | |
raise BufferEmptyException.new if empty? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original challenge at https://launchschool.com/gists/0164b2eb