dodb.cr/spec/test-lists.cr

125 lines
2.7 KiB
Crystal
Raw Permalink Normal View History

require "spec"
require "../src/list.cr"
describe "DoubleLinkedList" do
it "add and remove values" do
list = DoubleLinkedList(Int32).new
list.push 1
list.to_s.should eq "[ 1 ]"
list.push 2
list.to_s.should eq "[ 1, 2 ]"
list << 3 << 4
list.to_s.should eq "[ 1, 2, 3, 4 ]"
list.insert_at(8, 1)
list.to_s.should eq "[ 1, 8, 2, 3, 4 ]"
list.insert_at(0, 0)
list.to_s.should eq "[ 0, 1, 8, 2, 3, 4 ]"
list.insert_at(5, 6)
list.to_s.should eq "[ 0, 1, 8, 2, 3, 4, 5 ]"
v = list.pop
v.value.should eq 5
list.to_s.should eq "[ 0, 1, 8, 2, 3, 4 ]"
v = list.pop
v.value.should eq 4
list.to_s.should eq "[ 0, 1, 8, 2, 3 ]"
v = list.pop
v.value.should eq 3
list.to_s.should eq "[ 0, 1, 8, 2 ]"
v = list.pop
v.value.should eq 2
list.to_s.should eq "[ 0, 1, 8 ]"
v = list.pop
v.value.should eq 8
list.to_s.should eq "[ 0, 1 ]"
v = list.pop
v.value.should eq 1
list.to_s.should eq "[ 0 ]"
v = list.pop
v.value.should eq 0
list.to_s.should eq "[ ]"
expect_raises DoubleLinkedList::OutOfBounds do
list.pop
end
expect_raises DoubleLinkedList::OutOfBounds do
list[0]
end
list.size.should eq 0
end
it "insert_at" do
list = DoubleLinkedList(Int32).new
list.insert_at 2, 0
list.insert_at 1, 0
list.insert_at 3, 2
list.insert_at 0, 0
list.to_s.should eq "[ 0, 1, 2, 3 ]"
end
it "reverse" do
list = DoubleLinkedList(Int32).new
list.reverse.to_s.should eq "[ ]"
list << 1 << 2 << 3 << 4
list.reverse.to_s.should eq "[ 4, 3, 2, 1 ]"
end
it "concat" do
list1 = DoubleLinkedList(Int32).new
list2 = DoubleLinkedList(Int32).new
list1 << 1 << 2
list2 << 3 << 4
list1.concat list2
list1.to_s.should eq "[ 1, 2, 3, 4 ]"
end
it "+" do
list1 = DoubleLinkedList(Int32).new
list2 = DoubleLinkedList(Int32).new
list1 << 1 << 2
list2 << 3 << 4
list3 = list1 + list2
list1.to_s.should eq "[ 1, 2 ]"
list2.to_s.should eq "[ 3, 4 ]"
list3.to_s.should eq "[ 1, 2, 3, 4 ]"
end
it "shift" do
list = DoubleLinkedList(Int32).new
list << 1 << 2 << 3 << 4
list.shift.value.should eq 1
list.shift.value.should eq 2
list.shift.value.should eq 3
list.shift.value.should eq 4
end
it "unshift" do
list = DoubleLinkedList(Int32).new
list.unshift 1
list.unshift 2
list.unshift 3
list.unshift 4
list.pop
node = list.unshift 4
list.to_s.should eq "[ 4, 4, 3, 2 ]"
list.delete node
list.to_s.should eq "[ 4, 3, 2 ]"
end
it "peek" do
list = DoubleLinkedList(Int32).new
list << 1 << 2 << 3 << 4
list.peek.value.should eq 4
list.pop
list.peek.value.should eq 3
end
it "delete_at" do
list = DoubleLinkedList(Int32).new
list << 1 << 2 << 3 << 4
list.delete_at(2).value.should eq 3
list.to_s.should eq "[ 1, 2, 4 ]"
end
end