Skip to content

Commit

Permalink
Deduplicate when adding new elements to unique list
Browse files Browse the repository at this point in the history
  • Loading branch information
excid3 committed Dec 3, 2021
1 parent e326fc3 commit d5857e3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/kredis/types/unique_list.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,25 @@ class Kredis::Types::UniqueList < Kredis::Types::List
attr_accessor :typed, :limit

def prepend(elements)
elements = Array(elements).flatten.uniq
return if elements.empty?

multi do
remove elements
super
ltrim 0, (limit - 1) if limit
end if Array(elements).flatten.any?
end
end

def append(elements)
elements = Array(elements).flatten.uniq
return if elements.empty?

multi do
remove elements
super
ltrim -limit, -1 if limit
end if Array(elements).flatten.any?
end
end
alias << append
end
10 changes: 10 additions & 0 deletions test/types/unique_list_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,14 @@ class UniqueListTest < ActiveSupport::TestCase
@list.prepend(%w[ 6 7 8 ])
assert_equal %w[ 8 7 6 5 4 ], @list.elements
end

test "appending array with duplicates" do
@list.append(%w[ 1 1 1 ])
assert_equal %w[ 1 ], @list.elements
end

test "prepending array with duplicates" do
@list.prepend(%w[ 1 1 1 ])
assert_equal %w[ 1 ], @list.elements
end
end

0 comments on commit d5857e3

Please sign in to comment.