Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for set difference #14

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 40 additions & 1 deletion lib/kredis/types/set.rb
@@ -1,5 +1,8 @@
class Kredis::Types::Set < Kredis::Types::Proxying
proxying :smembers, :sadd, :srem, :multi, :del, :sismember, :scard, :spop
proxying :smembers, :sadd, :srem, :multi, :del, :sismember, :scard, :spop,
:sdiff, :sdiffstore,
:sunion, :sunionstore,
:sinter, :sinterstore

attr_accessor :typed

Expand Down Expand Up @@ -39,4 +42,40 @@ def take
def clear
del
end

def -(value)
diff value
end

def diff(value, store: nil)
if store
store.sdiffstore key, value.key
else
sdiff value.key
end
end

def &(value)
intersection value
end

def intersection(value, store: nil)
if store
store.sinterstore key, value.key
else
sinter value.key
end
end

def +(value)
union value
end

def union(value, store: nil)
if store
store.sunionstore key, value.key
else
sunion value.key
end
end
end
54 changes: 54 additions & 0 deletions test/types/set_test.rb
Expand Up @@ -63,6 +63,60 @@ class SetTest < ActiveSupport::TestCase
assert_equal [], @set.members
end

test "-" do
@set.add %w[1 2 3 4 5]
subset = Kredis.set "otherset"
subset.add %w[2 3 4]
assert_equal (@set - subset), %w[1 5]
end

test "diff" do
@set.add %w[1 2 3 4 5]
subset = Kredis.set "otherset"
subset.add %w[2 3 4]
assert_equal (@set.diff(subset)), %w[1 5]

result = Kredis.set "resultset"
@set.diff(subset, store: result)
assert_equal result.members, %w[1 5]
end

test "+" do
@set.add %w[1 2 3 4 5]
otherset = Kredis.set "otherset"
otherset.add %w[5 6 7 8 9]
assert_equal (@set + otherset), %w[1 2 3 4 5 6 7 8 9]
end

test "union" do
@set.add %w[1 2 3 4 5]
otherset = Kredis.set "otherset"
otherset.add %w[5 6 7 8 9]
assert_equal (@set.union(otherset)), %w[1 2 3 4 5 6 7 8 9]

result = Kredis.set "resultset"
@set.union(otherset, store: result)
assert_equal result.members, %w[1 2 3 4 5 6 7 8 9]
end

test "&" do
@set.add %w[1 2 3 4 5]
otherset = Kredis.set "otherset"
otherset.add %w[4 5 6 7]
assert_equal (@set & otherset), %w[4 5]
end

test "intersection" do
@set.add %w[1 2 3 4 5]
otherset = Kredis.set "otherset"
otherset.add %w[4 5 6 7]
assert_equal (@set.intersection(otherset)), %w[4 5]

result = Kredis.set "resultset"
@set.intersection(otherset, store: result)
assert_equal result.members, %w[4 5]
end

test "typed as floats" do
@set = Kredis.set "mylist", typed: :float

Expand Down