Created
October 9, 2011 17:55
-
-
Save marioaquino/1273956 to your computer and use it in GitHub Desktop.
Simple List Kata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
class List | |
def add(item) | |
new_item = Item.new(item, @tail) | |
@tail = new_item | |
end | |
def delete(item) | |
if item == @tail | |
@tail = item.next | |
return | |
end | |
val = @tail | |
prev = nil | |
until val == item | |
prev = val | |
val = val.next | |
end | |
prev.next = val.next unless val.nil? | |
end | |
def find(item) | |
return nil unless @tail | |
val = @tail | |
until val.nil? | |
return val if val.value == item | |
val = val.next | |
end | |
end | |
def values | |
vals = [] | |
val = @tail | |
until val.nil? | |
vals.insert(0, val.value) | |
val = val.next | |
end | |
vals | |
end | |
class Item | |
attr_reader :value, :next | |
attr_writer :next | |
def initialize(value, next_item = nil) | |
@value = value | |
@next = next_item | |
end | |
end | |
end | |
class ListTest < Test::Unit::TestCase | |
def test_behavior | |
list = List.new | |
assert_nil(list.find("fred")) | |
list.add("fred") | |
assert_equal("fred", list.find("fred").value()) | |
assert_nil(list.find("wilma")) | |
list.add("wilma") | |
assert_equal("fred", list.find("fred").value()) | |
assert_equal("wilma", list.find("wilma").value()) | |
assert_equal(["fred", "wilma"], list.values()) | |
list = List.new | |
list.add("fred") | |
list.add("wilma") | |
list.add("betty") | |
list.add("barney") | |
assert_equal(["fred", "wilma", "betty", "barney"], list.values()) | |
list.delete(list.find("wilma")) | |
assert_equal(["fred", "betty", "barney"], list.values()) | |
list.delete(list.find("barney")) | |
assert_equal(["fred", "betty"], list.values()) | |
list.delete(list.find("fred")) | |
assert_equal(["betty"], list.values()) | |
list.delete(list.find("betty")) | |
assert_equal([], list.values()) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment