polytree/deque.coffee

44 lines
1.3 KiB
CoffeeScript
Raw Normal View History

2021-04-19 04:07:31 +00:00
# Roughly following https://learnersbucket.com/tutorials/data-structures/implement-deque-data-structure-in-javascript/
export default class Deque
constructor: ->
@clear()
insertLeft: (elm) -> # Add an item on the left
if @left_full > 0
@items[--@left_full] = elm
else
@right_open++
@items.unshift elm
insertRight: (elm) -> # Add an item on the right of the list
@items[@right_open++] = elm
removeLeft: -> # Remove the item from the left
@nonempty() and @items[@left_full++]
removeRight: -> # Remove the item from the right
@nonempty() and @items[--@right_open]
left: -> # Peek the leftmost element
@nonempty and @items[@left_full]
right: -> # Peek the last element
@nonempty and @items[@right_open - 1]
nonempty: -> # Returns null if no elements
(@right_open > @left_full) or null
empty: -> # Returns null if any elements
(@right_open is @left_full) or null
size: -> # Number of elements
@right_open - @left_full
clear: -> # Remove all elements
@right_open = @left_full = 0
@items = []
toString: ->
"<#{@items[@left...@right].join(",")}>"