add Replace()
This commit is contained in:
parent
3771637d65
commit
9d5bd04429
10
deque.go
10
deque.go
|
@ -216,6 +216,16 @@ func (q *Deque) Remove(i int) interface{} {
|
|||
return elem
|
||||
}
|
||||
|
||||
// Replace replaces the element at position i with the given element. Accepts
|
||||
// only non-negative index values, and panics if index is out of range
|
||||
func (q *Deque) Replace(i int, elem interface{}) {
|
||||
if i < 0 || i >= q.count {
|
||||
panic("deque: Remove() called with index out of range")
|
||||
}
|
||||
// bitwise modulus
|
||||
q.buf[(q.head+i)&(len(q.buf)-1)] = elem
|
||||
}
|
||||
|
||||
// Clear removes all elements from the queue, but retains the current capacity.
|
||||
// The queue will not be resized smaller as long as items are only added.
|
||||
// Only when items are removed is the queue subject to getting resized smaller.
|
||||
|
|
|
@ -395,6 +395,28 @@ func TestRemove(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestReplace(t *testing.T) {
|
||||
var q Deque
|
||||
q.PushBack("a")
|
||||
q.PushBack("b")
|
||||
q.PushBack("c")
|
||||
|
||||
q.Replace(0, "A")
|
||||
if q.Front() != "A" {
|
||||
t.Error("expected A at front")
|
||||
}
|
||||
|
||||
q.Replace(q.Len()-1, "C")
|
||||
if q.Back() != "C" {
|
||||
t.Error("expected C at back")
|
||||
}
|
||||
|
||||
q.Replace(1, "-")
|
||||
if q.Peek(1) != "-" {
|
||||
t.Error("expected - at position 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeekOutOfRangePanics(t *testing.T) {
|
||||
var q Deque
|
||||
|
||||
|
@ -498,6 +520,24 @@ func TestRemoveOutOfRangePanics(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestReplaceOutOfRangePanics(t *testing.T) {
|
||||
var q Deque
|
||||
|
||||
assertPanics(t, "should panic when replacing in empty queue", func() {
|
||||
q.Replace(0, "x")
|
||||
})
|
||||
|
||||
q.PushBack("A")
|
||||
|
||||
assertPanics(t, "should panic when replacing at negative index", func() {
|
||||
q.Replace(-1, "Z")
|
||||
})
|
||||
|
||||
assertPanics(t, "should panic when replacing out of range", func() {
|
||||
q.Replace(1, "Y")
|
||||
})
|
||||
}
|
||||
|
||||
func assertPanics(t *testing.T, name string, f func()) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
|
|
Loading…
Reference in a new issue