Skip to content

Commit

Permalink
Add ZDIFF command
Browse files Browse the repository at this point in the history
Signed-off-by: Devansh Singh <[email protected]>
  • Loading branch information
Devansh3712 committed Mar 31, 2024
1 parent 8e0d269 commit 8088da5
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
3 changes: 3 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const (
// Sorted set commands
CMD_ZADD = "ZADD"
CMD_ZCARD = "ZCARD"
CMD_ZDIFF = "ZDIFF"
CMD_ZREMOVE = "ZREMOVE"
CMD_ZMEMBERS = "ZMEMBERS"
)
Expand Down Expand Up @@ -148,6 +149,8 @@ func (s *Server) HandleCommand() {
s.zAdd(cmd)
case CMD_ZCARD:
s.zCard(cmd)
case CMD_ZDIFF:
s.zDiff(cmd)
case CMD_ZREMOVE:
s.zRemove(cmd)
case CMD_ZMEMBERS:
Expand Down
15 changes: 15 additions & 0 deletions server/zset.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,18 @@ func (s *Server) zRemove(cmd Command) {
return
}
}

func (s *Server) zDiff(cmd Command) {
if len(cmd.Args) < 2 {
cmd.error(ErrNotEnoughArgs)
return
}
elements, err := s.DB.ZDiff(cmd.Args[0], cmd.Args[1])
if err != nil {
cmd.error(err)
return
}
for index, element := range elements {
cmd.write(fmt.Sprintf("%d) %s", index+1, element))
}
}
23 changes: 22 additions & 1 deletion store/zset.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package store

import "github.com/Devansh3712/tandb/zset"
import (
"fmt"

"github.com/Devansh3712/tandb/zset"
)

func (s *Store) ZAdd(set, key string) {
s.Mutex.Lock()
Expand Down Expand Up @@ -46,3 +50,20 @@ func (s *Store) ZRemove(set, key string) error {
}
return value.Remove(key)
}

func (s *Store) ZDiff(s1, s2 string) ([]string, error) {
s.Mutex.RLock()
defer s.Mutex.RUnlock()

v1, ok := s.ZSets[s1]
if !ok {
return nil, fmt.Errorf("the set %s does not exist", s1)
}
v2, ok := s.ZSets[s2]
if !ok {
return nil, fmt.Errorf("the set %s does not exist", s2)
}

diff := v1.Difference(v2)
return diff.Members(), nil
}

0 comments on commit 8088da5

Please sign in to comment.