Skip to content

Commit

Permalink
Add add-first to Deque (#1843)
Browse files Browse the repository at this point in the history
  • Loading branch information
Erik Corry authored Oct 2, 2023
1 parent 301261c commit 66c3a04
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/core/collections.toit
Original file line number Diff line number Diff line change
Expand Up @@ -3200,10 +3200,25 @@ class Deque implements Collection:
if first == backing.size: throw "OUT_OF_RANGE"
result := backing[first]
backing[first] = null
first_ = first + 1
first_++
shrink-if-needed_
return result

add-first element -> none:
first := first_
if first == 0:
padding-size := (backing_.size >> 1) + 1
new_size := backing_.size + padding-size
// Pad both ends so we are not inefficient in the case where the next
// operation adds to the end.
new_backing := List_.private_ (new_size + padding-size) new_size
new_backing.replace padding-size backing_
backing_ = new_backing
first = padding-size
first--
backing_[first] = element
first_ = first

shrink-if-needed_ -> none:
backing := backing_
first := first_
Expand Down
7 changes: 7 additions & 0 deletions tests/deque-test.toit
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ test-deque:
expect-equals 13 deque.remove-first
expect deque.size == 5

deque.add-first 55
expect-equals 55 deque.first
deque.add-first 103
expect-equals 103 deque.first
expect-equals 103 deque.remove-first
expect-equals 55 deque.remove-first

expect-equals 1 deque.first
expect-equals 1 deque.remove-first
expect deque.size == 4
Expand Down

0 comments on commit 66c3a04

Please sign in to comment.