Skip to content

Added memoize, once, and after, from Underscore.js #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion lib/underscore.lua
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
local Underscore = { funcs = {} }
Underscore.__index = Underscore

local nilValue = {}

function Underscore.__call(_, value)
return Underscore:new(value)
end
Expand Down Expand Up @@ -380,6 +382,46 @@ function Underscore.funcs.curry(func, argument)
end
end

function Underscore.funcs.memoize(func, hasher)
local memo = {}
hasher = hasher or identity;
return function(...)
local key = hasher(this, ...)
if memo[key] ~= nil then
if memo[key] == nilValue then
return nil
else
return memo[key]
end
else
local result = func(...)
memo[key] = result == nil and nilValue or result
return result
end
end
end

function Underscore.funcs.once(func)
local ran = false
local memo
return function(...)
if not ran then
memo = func(...)
ran = true
end
return memo
end
end
-- Returns a function that will only be executed upon being called N times.
function Underscore.funcs.after(times, func) {
return function(...) {
times = times - 1
if times < 1 then
return func(...)
end
end
end

function Underscore.functions()
return Underscore.keys(Underscore.funcs)
end
Expand Down Expand Up @@ -422,4 +464,4 @@ end

wrap_functions_for_oo_support()

return Underscore:new()
return Underscore:new()