Module:Util/tables/iteratee

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search

An iteratee is a function called by an iterating function (such as map or filter) as it iterates over an array. The iteratee is called for each array element, with the element as its sole argument.

When iterating over arrays of objects, the iteratee function on this page helps create iteratees from shorthands:

  • The property iteratee is created from a string value that names an object property. The iteratee takes an object and returns its value for that property.
  • The isMatch iteratee is created from an object (object A). The iteratee takes an object (object B) and returns true if B matches A. B matches A if it has all the same property values as A. B may have additional properties that A doesn't have.

This function is only intended for use by iterator functions in Module:Util/tables and should not be used directly.

Definition

iteratee(val)

Returns

  • An iteratee function

Examples

#InputOutputStatus
Iteratee from string (property shorthand)
1
local game = {
  abbr = "OoA", 
  title = "Oracle of Ages",
}
local iteratee = util.tables.iteratee("abbr")
return iteratee(game)
"OoA"
2
local game = {
  title = "Bayonetta",
}
local iteratee = util.tables.iteratee("abbr")
return iteratee(game)
nil
Iteratee from table (isMatch shorthand)
3
local game = {
  abbr = "OoA",
  title = "Oracle of Ages",
}
local iteratee = util.tables.iteratee({ abbr = "OoA" })
return iteratee(game)
true
4
local game = {
  abbr = "OoA",
  title = "Oracle of Ages",
}
local iteratee = util.tables.iteratee({ abbr = "OoS" })
return iteratee(game)
false

local function property(key)
	return function(tbl)
		return tbl[key]
	end
end

local function match(src)
	return function(tbl)
		for k, v in pairs(src) do
			if type(v) == "table" and not isMatch(tbl[k], v) then
				return false
			end
			if v ~= tbl[k] then
				return false
			end
		end
		return true
	end
end

local function identity(val)
	return val
end

local function iteratee(val)
	if type(val) == "function" then
		return val
	end
	if type(val) == "string" or type(val) == "number" then
		return property(val)
	end
	if type(val) == "table" then
		return match(val)
	end
	return identity
end

return iteratee