-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(commands): add count argument to lpop and remove key when list is…
… empty
- Loading branch information
Showing
2 changed files
with
76 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,40 @@ | ||
import { convertStringToBuffer } from '../commands-utils/convertStringToBuffer' | ||
|
||
export function lpop(key) { | ||
export function lpop(key, count) { | ||
if (this.data.has(key) && !(this.data.get(key) instanceof Array)) { | ||
throw new Error(`Key ${key} does not contain a list`) | ||
} | ||
const list = this.data.get(key) || [] | ||
|
||
const item = list.length > 0 ? list.shift() : null | ||
if (list.length === 0) { | ||
return null | ||
} | ||
|
||
if (count) { | ||
const items = list.slice(0, count) | ||
const remainingItems = list.slice(count) | ||
|
||
this.data.set(key, list) | ||
if (remainingItems.length > 0) { | ||
this.data.set(key, remainingItems) | ||
} else { | ||
this.data.delete(key) | ||
} | ||
|
||
return items | ||
} | ||
|
||
const item = list.shift() | ||
|
||
if (list.length > 0) { | ||
this.data.set(key, list) | ||
} else { | ||
this.data.delete(key) | ||
} | ||
|
||
return item | ||
} | ||
|
||
export function lpopBuffer(key) { | ||
const val = lpop.apply(this, [key]) | ||
export function lpopBuffer(key, count) { | ||
const val = lpop.apply(this, [key, count]) | ||
return convertStringToBuffer(val) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters