Skip to content

Commit

Permalink
Implement List#index (aliased as #find_index).
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Harris committed Jan 26, 2010
1 parent 2d8569d commit dd1099d
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
16 changes: 16 additions & 0 deletions lib/hamster/list.rb
Expand Up @@ -465,6 +465,22 @@ def slice(from, length = Undefined)
end
def_delegator :self, :slice, :[]

def index(object)
# def index(object, i = 0)
# return nil if empty?
# return i if object == head
# tail.index(object, i + 1)
i = 0
list = self
loop do
return nil if list.empty?
return i if object == list.head
i += 1
list = list.tail
end
end
def_delegator :self, :index, :find_index

def eql?(other)
# return true if other.equal?(self)
# return false unless other.is_a?(List)
Expand Down
58 changes: 58 additions & 0 deletions spec/hamster/list/index_spec.rb
@@ -0,0 +1,58 @@
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

require 'hamster/list'

describe Hamster::List do

[:index, :find_index].each do |method|

describe "##{method}" do

describe "on a really big list" do

before do
@list = Hamster.interval(0, STACK_OVERFLOW_DEPTH)
end

it "doesn't run out of stack" do
lambda { @list.send(method, nil) }.should_not raise_error
end

end

[
[[], "A", nil],
[[], nil, nil],
[["A"], "A", 0],
[["A"], "B", nil],
[["A"], nil, nil],
[["A", "B", nil], "A", 0],
[["A", "B", nil], "B", 1],
[["A", "B", nil], nil, 2],
[["A", "B", nil], "C", nil],
[[2], 2, 0],
[[2], 2.0, 0],
[[2.0], 2.0, 0],
[[2.0], 2, 0],
].each do |values, item, expected|

describe "looking for #{item.inspect} in #{values.inspect}" do

before do
list = Hamster.list(*values)
@result = list.send(method, item)
end

it "returns #{expected.inspect}" do
@result.should == expected
end

end

end

end

end

end
2 changes: 1 addition & 1 deletion yak-stack.txt
@@ -1,7 +1,7 @@
* Make List#size not O(n)!
* Make List#sort/#sort_by efficient :)
* Make Set#sort/#sort_by efficient :)
* Add List #hash, #fill, #sample, #index (#find_index), #insert, #insert_by, #to_set, #permutation (aliased as #permutations), #subsequences, #transpose
* Add List #hash, #fill, #sample, #insert, #insert_by, #to_set, #permutation (aliased as #permutations), #subsequences, #transpose
* Add Set #hash, #one?, #cycle, #sample, #max(imum), #min(imum), #flatten
* Add Hash #hash, #find (#detect), #count, #partition, #one?, #sort, #sort_by, #max(imum), #min(imum), #cycle, #clear
* Implement Set#union aliased as #| and #+
Expand Down

0 comments on commit dd1099d

Please sign in to comment.