mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-25 23:24:35 +00:00
[modified] functional.remove
renamed to functional.remove_if
, moved functional.group_by
, more documentation added
This commit is contained in:
parent
2d24d8e913
commit
e6a59460bd
@ -70,6 +70,7 @@ function functional.remap(t, f)
|
||||
end
|
||||
|
||||
--filters a sequence
|
||||
-- returns a table containing items where f(v) returns truthy
|
||||
function functional.filter(t, f)
|
||||
local r = {}
|
||||
for i,v in ipairs(t) do
|
||||
@ -80,8 +81,10 @@ function functional.filter(t, f)
|
||||
return r
|
||||
end
|
||||
|
||||
-- inverse of filter - returns a table containing items where f(v) returns false.
|
||||
function functional.remove(t, f)
|
||||
-- complement of filter
|
||||
-- returns a table containing items where f(v) returns falsey
|
||||
-- nil results are included so that this is an exact complement of filter; consider using partition if you need both!
|
||||
function functional.remove_if(t, f)
|
||||
local r = {}
|
||||
for i, v in ipairs(t) do
|
||||
if not f(v, i) then
|
||||
@ -91,7 +94,8 @@ function functional.remove(t, f)
|
||||
return r
|
||||
end
|
||||
|
||||
--partitions a sequence based on filter criteria
|
||||
--partitions a sequence into two, based on filter criteria
|
||||
--simultaneous filter and remove_if
|
||||
function functional.partition(t, f)
|
||||
local a = {}
|
||||
local b = {}
|
||||
@ -105,6 +109,20 @@ function functional.partition(t, f)
|
||||
return a, b
|
||||
end
|
||||
|
||||
-- returns a table where the elements in t are grouped into sequential tables by the result of f on each element.
|
||||
-- more general than partition, but requires you to know your groups ahead of time (or use numeric grouping) if you want to avoid pairs!
|
||||
function functional.group_by(t, f)
|
||||
local result = {}
|
||||
for i, v in ipairs(t) do
|
||||
local group = f(v)
|
||||
if result[group] == nil then
|
||||
result[group] = {}
|
||||
end
|
||||
table.insert(result[group], v)
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
--zips two sequences together into a new table, based on another function
|
||||
--iteration limited by min(#t1, #t2)
|
||||
--function receives arguments (t1, t2, i)
|
||||
@ -274,17 +292,4 @@ function functional.find_match(t, f)
|
||||
return nil
|
||||
end
|
||||
|
||||
-- returns a table where the elements in t are grouped by the result of f on each element.
|
||||
function functional.group_by(t, f)
|
||||
local result = {}
|
||||
for i, v in ipairs(t) do
|
||||
local group = f(v)
|
||||
if result[group] == nil then
|
||||
result[group] = {}
|
||||
end
|
||||
table.insert(result[group], v)
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
return functional
|
||||
|
Loading…
Reference in New Issue
Block a user