Created
June 2, 2015 20:49
-
-
Save kyle-hall/6b6c0c847c552e475e2b to your computer and use it in GitHub Desktop.
functional CircularBuffer implementation
This file contains hidden or 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
| #My implementation of a (mostly) functional version of a CircularBuffer data structure | |
| class CircularBuffer | |
| def initialize (size,arr,head,tail) | |
| @cbuff = arr | |
| @size = size | |
| @head = head | |
| @tail = tail | |
| end | |
| def push(elem) | |
| #when the buffer is full, just return a copy of this instance | |
| if @head + 1 % @size == @tail return CiruclarBuffer.new(@size,@cbuff,@head,@tail) end | |
| CiruclarBuffer.new(@size,@cbuff.insert(@head,elem),(@head+1) % @size,@tail) | |
| end | |
| def take() | |
| if @head == @tail CiruclarBuffer.new(@size,@cbuff,@head,@tail) end | |
| CiruclarBuffer.new(@size,@cbuff.delete_at(@tail),@head,(@tail + 1) % @size) | |
| end | |
| def size | |
| @size | |
| end | |
| #this method returns the distance between head and tail, i.e. the number | |
| #of indices which hold actual values | |
| def length | |
| if @head > @tail | |
| return @head - @tail | |
| elsif @tail > @head | |
| return (@head + @size) - @tail | |
| else | |
| return 0 | |
| end | |
| end | |
| def peek | |
| @cbuff[@head] | |
| end | |
| def head | |
| @head | |
| end | |
| def tail | |
| @tail | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment