Module:UtilsFunction: Difference between revisions

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search
No edit summary
m (Changed protection level for "Module:UtilsFunction": Critical wiki page ([Edit=Allow only administrators] (indefinite) [Move=Allow only administrators] (indefinite)))
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
local p = {}
local p = {}


function p.noop(...)  
function p.identity(...)
return ...  
return ...
end
 
function p.memoize(fn)
local cache = {}
return function(...)
local key = mw.dumpObject({...})
if not cache[key] then
cache[key] = fn(...)
end
return cache[key]
end
end
end


Line 11: Line 22:
end
end


-- @args {fn1, fn2, ..., fnN}
function p.noop()
-- @returns A single function whose arguments are passed to fn1. Output of fn1 is passed to fn2, and so on.
return nil
-- Similar to https://lodash.com/docs/#flow
end
 
function p.peek(tbl)
mw.logObject(tbl)
return tbl
end
 
function p.pipe(...)
function p.pipe(...)
local functions = {...}
local state = {...}
return function(...)
return function(functions)
local state = {...}
for _, fn in ipairs(functions) do
for _, fn in ipairs(functions) do
state = {fn(unpack(state))}
state = {fn(unpack(state))}

Latest revision as of 18:33, 4 August 2020

The functions in this module return other functions, namely iterators. It also contains utility functions for functional programming.


local p = {}

function p.identity(...)
	return ...
end

function p.memoize(fn)
	local cache = {}
	return function(...)
		local key = mw.dumpObject({...})
		if not cache[key] then
			cache[key] = fn(...)
		end
		return cache[key]
	end
end

function p.negate(fn)
	return function(...)
		return not fn(...)
	end
end

function p.noop() 
	return nil
end

function p.peek(tbl)
	mw.logObject(tbl)
	return tbl
end

function p.pipe(...)
	local state = {...}
	return function(functions)
		for _, fn in ipairs(functions) do
			state = {fn(unpack(state))}
		end
		return unpack(state)
	end
end

-- http://lua-users.org/wiki/RangeIterator
function p.range(a, b, step)
  if not b then
    b = a
    a = 1
  end
  step = step or 1
  local f =
    step > 0 and
      function(_, lastvalue)
        local nextvalue = lastvalue + step
        if nextvalue <= b then return nextvalue end
      end or
    step < 0 and
      function(_, lastvalue)
        local nextvalue = lastvalue + step
        if nextvalue >= b then return nextvalue end
      end or
      function(_, lastvalue) return lastvalue end
  return f, nil, a - step
end

return p