Home
Random
Recent changes
Special pages
Community portal
Preferences
About Stockhub
Disclaimers
Search
User menu
Talk
Contributions
Create account
Log in
Editing
Module:Sandbox/Artoria2e5/CacheUtils
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
-- Cached function decorators. -- lru -- lfu -- rr local defaultsize = 128 -- An ordered dict implementation. local orderedDict = {} function orderedDict.create(argDict, argOrder) if (#dict) ~= (#order) then return nil end -- grrr, this won't work if I want (amortized) O(1) removal -- TODO: Use a double-linked map of the form table<key:T, node<val:T, prev:node, next:node>> local dict = {} for k, v in pairs(argDict) do dict[k] = { ['v'] = v } end local order = {} -- tableArray local function len(this) return #dict end local function newindex(this, k, v) dict[k] = { ['v'] = v } table.insert(order, k) end local function leak() return dict, order end local ret = {} setmetatable(ret, { ["__len"] = len, ["__newindex"] = __newindex, -- FIXME ["__index"] = dict, ["__mwint__leak"] = leak, }) return ret end -- These need to go into the metatable. They interfere with indexing. function orderedDict:has(od, k) local dict, order, nils = getmetatable(od).__mwint__leak() return (dict[k] ~= nil) or (nils[k]) end function orderedDict:pop(od, k) local dict, order, nils = getmetatable(od).__mwint__leak() if orderedDict:has(od, k) then v = dict[k] table.remove(dict, k) if v == nil then table.remove(nils, k) end else return nil, false end end local function lru_cache(func, size) size = size or defaultsize memo = OrderedDict.create() end return { ["lru"] = lru_cache, ["_"] = { ["orderedDict"] = orderedDict } }
Summary:
Please note that all contributions to Stockhub may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Stockhub:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Template used on this page:
Module:Sandbox/Artoria2e5/CacheUtils/doc
(
edit
)