Skip to content

Instantly share code, notes, and snippets.

@wolf81
Created May 8, 2021 14:48
Show Gist options
  • Select an option

  • Save wolf81/6a4f499913c87dae22eab10ebd126c01 to your computer and use it in GitHub Desktop.

Select an option

Save wolf81/6a4f499913c87dae22eab10ebd126c01 to your computer and use it in GitHub Desktop.
Simple (jitter) buffer
local buffer = Class {}
function buffer:init(size, sort)
assert(size ~= nil, "a size is required to create a buffer")
self._size = math.max(size or DEFAULT_BUFFER_SIZE, 1)
self._items = {}
self._sort = sort or function(left, right) return true end
end
-- remove last item from buffer
function buffer:dequeue()
return table.remove(self._items)
end
function buffer:clear()
self._items = {}
end
-- add item to the buffer & sort after adding item when sort function defined in constructor
-- if buffer is full, last item is removed
function buffer:enqueue(item)
table.insert(self._items, item)
table.sort(self._items, self._sort)
if #self._items > self._size then table.remove(self._items) end
end
function buffer:isFull()
return #self._items == self._size
end
function buffer:isEmpty()
return #self._items == 0
end
return buffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment