Last active
February 3, 2017 11:42
-
-
Save kosmikko/335bebbae2d8ee92e3d36ea22689076e to your computer and use it in GitHub Desktop.
Redis script to pop the last element from LIST_KEY that doesn't match SEARCH arg
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
-- pop the last element from LIST_KEY that doesn't match SEARCH arg | |
local LIST_KEY = KEYS[1] | |
local SEARCH = ARGV[1] | |
-- avoid the expensive LRANGE by peeking the last element | |
local last = redis.call('LINDEX', LIST_KEY, -1) | |
if not (string.find(last, SEARCH)) then | |
redis.call('RPOP', LIST_KEY) | |
return last | |
end | |
-- last element is matching -> need to loop though list | |
local items = redis.call('LRANGE', LIST_KEY, 0, -1) | |
for i=#items, 1, -1 do | |
local value = items[i] | |
if not (string.find(value, SEARCH)) then | |
redis.call('LREM', LIST_KEY, -1, value) | |
return value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment