Module:Util/tables/find

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

find(tbl, iteratee)

Returns

  • The value if found, else nil
  • The index of the value found, else nil

Examples

#InputOutputStatus
1
local args = {"foo", "bar", "baz"}
return util.tables.find(args, util.strings._startsWith("b"))
"bar"
2
2
local args = {"foo", "quux", "quux"}
return util.tables.find(args, util.strings._startsWith("b"))
nil
nil
3
find(
  {
    {
      canon = false,
      game = "Tingle's Rosy Rupeeland",
    },
    {
      canon = true,
      game = "The Wind Waker",
    },
    {
      canon = true,
      game = "Breath of the Wild",
    },
  },
  "canon"
)
{
  canon = true,
  game = "The Wind Waker",
}
2
4
find(
  {
    {
      canon = false,
      game = "Tingle's Rosy Rupeeland",
      type = "spinoff",
    },
    {
      canon = true,
      game = "Twilight Princess HD",
      type = "remake",
    },
    {
      canon = true,
      game = "Breath of the Wild",
      type = "main",
    },
  },
  {
    canon = true,
    type = "main",
  }
)
{
  canon = true,
  game = "Breath of the Wild",
  type = "main",
}
3

local iteratee = require("Module:Util/tables/iteratee")

local function find(tbl, predicate)
	predicate = iteratee(predicate)
	for i, v in ipairs(tbl) do
		if predicate(v) then
			return v, i
		end
	end
	return nil, nil
end

return find