Skip to content

Commit

Permalink
Changed list api to make finding more explicit
Browse files Browse the repository at this point in the history
  • Loading branch information
tredfern committed Dec 26, 2018
1 parent d6792c5 commit 3470a15
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
20 changes: 10 additions & 10 deletions src/list.lua
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ function list:index_of(item)
return nil
end

function list:first(search)
if search == nil then
return self[1]
end

function list:find(search)
for _, v in ipairs(self) do
if search(v) then
return v
Expand All @@ -43,11 +39,7 @@ function list:first(search)
return nil
end

function list:last(search)
if search == nil then
return self[#self]
end

function list:find_last(search)
for i = #self, 1, -1 do
if search(self[i]) then
return self[i]
Expand All @@ -56,6 +48,14 @@ function list:last(search)
return nil
end

function list:first()
return self[1]
end

function list:last()
return self[#self]
end

function list:contains(item)
return self:index_of(item) ~= nil
end
Expand Down
8 changes: 4 additions & 4 deletions src/list_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -59,25 +59,25 @@ describe("List", function()

it("can have a filter for first item that returns the first item that matches the filter", function()
local b = list:new({2, 4, 6, 8 })
local found = b:first(function(c) return c % 2 == 0 end)
local found = b:find(function(c) return c % 2 == 0 end)
assert.equals(2, found)
end)

it("it returns nil on a search if it cannot find any item", function()
local b = list:new({"one", "two", "three"})
local none = b:first(function(c) return c == "four" end)
local none = b:find(function(c) return c == "four" end)
assert.equals(nil, none)
end)

it("can have a filter for last item that returns the last item that matches the filter", function()
local b = list:new({2, 4, 6, 8})
local found = b:last(function(c) return c % 2 == 0 end)
local found = b:find_last(function(c) return c % 2 == 0 end)
assert.equals(8, found)
end)

it("it returns nil on a search if it cannot find any item", function()
local b = list:new({"one", "two", "three"})
local none = b:last(function(c) return c == "four" end)
local none = b:find_last(function(c) return c == "four" end)
assert.equals(nil, none)
end)

Expand Down

0 comments on commit 3470a15

Please sign in to comment.