LRange returns a range of elements from a list associated with a key. The range is inclusive, including both the start and stop indices. If the key does not exist, an error is returned. If the list is empty, an error is returned. Negative indices can be used, where -1 represents the last element of
(key string, start int, stop int)
| 228 | // Negative indices can be used, where -1 represents the last element of the list, |
| 229 | // -2 represents the second last element, and so on. |
| 230 | func (l *ListStructure) LRange(key string, start int, stop int) ([]interface{}, error) { |
| 231 | // Get the list |
| 232 | lst, _, err := l.getListFromDB(key, false) |
| 233 | if err != nil { |
| 234 | return nil, err |
| 235 | } |
| 236 | |
| 237 | // Return error if the list is empty |
| 238 | if lst.Length == 0 { |
| 239 | return nil, ErrListEmpty |
| 240 | } |
| 241 | |
| 242 | // Calculate the correct indices |
| 243 | start = (start%lst.Length + lst.Length) % lst.Length |
| 244 | stop = (stop%lst.Length + lst.Length) % lst.Length |
| 245 | |
| 246 | // Return empty if the range length is less than 1 |
| 247 | if stop < start { |
| 248 | return nil, nil |
| 249 | } |
| 250 | |
| 251 | nowNode := lst.Head |
| 252 | |
| 253 | for i := 0; i < start; i++ { |
| 254 | nowNode = nowNode.Next |
| 255 | } |
| 256 | result := make([]interface{}, 0, stop-start+1) |
| 257 | for i := start; i <= stop; i++ { |
| 258 | result = append(result, nowNode.Value) |
| 259 | nowNode = nowNode.Next |
| 260 | } |
| 261 | |
| 262 | return result, nil |
| 263 | } |
| 264 | |
| 265 | // LLen returns the size of a list associated with a key. |
| 266 | // If the key does not exist, an error is returned. |