mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-22 22:24:35 +00:00
[modified] functional.lua find_best changed to ipairs and added find_min and find_max better named alternatives
This commit is contained in:
parent
9422152181
commit
4bbbdf86d6
@ -241,13 +241,28 @@ function _table.min(t)
|
|||||||
return min
|
return min
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--return the element of the table that results in the lowest numeric value
|
||||||
|
--(function receives element and index respectively)
|
||||||
|
function _table.find_min(t, f)
|
||||||
|
local current = nil
|
||||||
|
local current_best = math.huge
|
||||||
|
for i, v in ipairs(t) do
|
||||||
|
v = f(v, i)
|
||||||
|
if v and v < current_best then
|
||||||
|
current_best = v
|
||||||
|
current = e
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return current
|
||||||
|
end
|
||||||
|
|
||||||
--return the element of the table that results in the greatest numeric value
|
--return the element of the table that results in the greatest numeric value
|
||||||
--(function receives element and key respectively, table evaluated in pairs order)
|
--(function receives element and index respectively)
|
||||||
function _table.find_best(t, f)
|
function _table.find_max(t, f)
|
||||||
local current = nil
|
local current = nil
|
||||||
local current_best = -math.huge
|
local current_best = -math.huge
|
||||||
for k,e in pairs(t) do
|
for i, v in ipairs(t) do
|
||||||
local v = f(e, k)
|
v = f(v, i)
|
||||||
if v and v > current_best then
|
if v and v > current_best then
|
||||||
current_best = v
|
current_best = v
|
||||||
current = e
|
current = e
|
||||||
@ -256,6 +271,9 @@ function _table.find_best(t, f)
|
|||||||
return current
|
return current
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--alias
|
||||||
|
_table.find_best = _table.find_max
|
||||||
|
|
||||||
--return the element of the table that results in the value nearest to the passed value
|
--return the element of the table that results in the value nearest to the passed value
|
||||||
--todo: optimise as this generates a closure each time
|
--todo: optimise as this generates a closure each time
|
||||||
function _table.find_nearest(t, f, v)
|
function _table.find_nearest(t, f, v)
|
||||||
|
Loading…
Reference in New Issue
Block a user