diff options
| -rw-r--r-- | handlers.go | 73 | ||||
| -rw-r--r-- | helpers.go | 10 | ||||
| -rw-r--r-- | main.go | 1 |
3 files changed, 83 insertions, 1 deletions
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 diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..fa38641 --- /dev/null +++ b/helpers.go @@ -0,0 +1,10 @@ +package main + +func listContains(list []string, target string) bool { + for _, item := range list { + if item == target { + return true + } + } + return false +}
\ No newline at end of file @@ -38,6 +38,7 @@ var commandRegistry = map[string]handlerFunc{ "TYPE": handleType, "DBSIZE": handleDbsize, "KEYS": handleKeys, + "LREM": handleLrem, } func main() { |
