From b523e77159b89cdb22a8e6e7f9d0046cd4269443 Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 8 Jul 2026 19:25:30 +0200 Subject: added LREM command --- handlers.go | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) (limited to 'handlers.go') diff --git a/handlers.go b/handlers.go index 13b2d11..305d526 100644 --- a/handlers.go +++ b/handlers.go @@ -633,7 +633,7 @@ func handleKeys(conn net.Conn, args []string) { if len(args) == 3 { val, err := strconv.Atoi(args[2]) if err != nil { - conn.Write(serializeRESP(errors.New("ERR value is not an integer"))) + conn.Write(serializeRESP(errors.New("value is not an integer"))) return } limit = val @@ -659,4 +659,75 @@ func handleKeys(conn net.Conn, args []string) { db.mu.Unlock() conn.Write(serializeRESP(matches)) +} +func handleLrem(conn net.Conn, args []string){ + + if len(args) != 4 { + conn.Write(serializeRESP(errors.New("wrong number of arguments for 'LREM'"))) + return + } + db.mu.Lock() + defer db.mu.Unlock() + + key := args[1] + count,err := strconv.Atoi(args[2]) + toBeRemoved := args[3] + + if err != nil { + conn.Write(serializeRESP(errors.New("value is not an integer"))) + return + } + item, exists:= db.data[key] + if !exists { + + } + list, ok := item.Value.([]string) + if !ok { + conn.Write(serializeRESP(errors.New("WRONGTYPE Operation against a key holding the wrong kind of value"))) + return + } + counter := 0 + absCount := count + if count < 0 { + absCount = -count + } + switch{ + case count == 0: + newList := []string{} + for i, value := range list { + if value == toBeRemoved{ + newList = append(list[:i], list[i+1:]...) + counter += 1 + } + } + list = newList + case count > 0: + newList := []string{} + for i, value := range list { + if counter == absCount{ + break + } + if value == toBeRemoved{ + newList = append(list[:i], list[i+1:]...) + counter += 1 + } + } + list = newList + case count < 0: + newList := []string{} + for i := len(list) - 1; i >= 0; i-- { + value := list[i] + if counter == absCount{ + break + } + if value == toBeRemoved{ + newList = append(list[:i], list[i+1:]...) + counter += 1 + } + } + list = newList + } + item.Value = list + db.data[key] = item + conn.Write(serializeRESP(counter)) } \ No newline at end of file -- cgit v1.2.3