mirror of
https://github.com/appgurueu/modlib.git
synced 2024-11-22 07:13:45 +01:00
Add func.memoize
This commit is contained in:
parent
479afb6c88
commit
f4b7eca18f
18
func.lua
18
func.lua
@ -1,6 +1,6 @@
|
||||
-- Localize globals
|
||||
local error, coroutine, math, modlib, unpack
|
||||
= error, coroutine, math, modlib, unpack
|
||||
local error, coroutine, math, modlib, unpack, select, setmetatable
|
||||
= error, coroutine, math, modlib, unpack, select, setmetatable
|
||||
|
||||
-- Set environment
|
||||
local _ENV = {}
|
||||
@ -35,6 +35,20 @@ function values(...)
|
||||
return function() return unpack(args) end
|
||||
end
|
||||
|
||||
function memoize(func)
|
||||
return setmetatable({}, {
|
||||
__index = function(self, key)
|
||||
local value = func(key)
|
||||
self[key] = value
|
||||
return value
|
||||
end,
|
||||
__call = function(self, arg)
|
||||
return self[arg]
|
||||
end,
|
||||
__mode = "k"
|
||||
})
|
||||
end
|
||||
|
||||
-- Equivalent to `for x, y, z in iterator, state, ... do callback(x, y, z) end`
|
||||
function iterate(callback, iterator, state, ...)
|
||||
local function loop(...)
|
||||
|
10
test.lua
10
test.lua
@ -53,6 +53,16 @@ do
|
||||
end
|
||||
assert(next(tab) == nil)
|
||||
assert(func.aggregate(func.add, 1, 2, 3) == 6)
|
||||
local called = false
|
||||
local function fun(arg)
|
||||
assert(arg == "test")
|
||||
local retval = called
|
||||
called = true
|
||||
return retval
|
||||
end
|
||||
local memo = func.memoize(fun)
|
||||
assert(memo(arg) == false)
|
||||
assert(memo(arg) == false)
|
||||
end
|
||||
|
||||
-- string
|
||||
|
Loading…
Reference in New Issue
Block a user