Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add last to lists
For simplicity, this does not strictly respect Array#last when nil or
false is passed, returning the last element instead of raising a
TypeError.

It also doesn't coerce the parameter into an int with to_int like
Array#last does.
  • Loading branch information
etiennebarrie committed Oct 6, 2022
commit 02c42fa9ca45485d56cfdae2a68826bb56ab6b6d
14 changes: 14 additions & 0 deletions lib/kredis/types/list.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,18 @@ def append(*elements)
def clear
del
end

def last(n = nil)
if n
if n == 0
[]
elsif n < 0
raise ArgumentError, "negative array size"
else
lrange(-n, -1)
end
else
lrange(-1, -1).first
end
end
end
12 changes: 12 additions & 0 deletions test/types/list_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ class ListTest < ActiveSupport::TestCase
assert_equal [], @list.elements
end

test "last" do
@list.append(%w[ 1 2 3 ])
assert_equal "3", @list.last
end

test "last(n)" do
@list.append(%w[ 1 2 3 ])
assert_equal %w[ 2 3 ], @list.last(2)
assert_equal [], @list.last(0)
assert_raises(ArgumentError) { @list.last(-2) }
end

test "typed as datetime" do
@list = Kredis.list "mylist", typed: :datetime

Expand Down