Added lume.reject(), updated tests and README.md

This commit is contained in:
rxi 2015-02-20 19:22:42 +00:00
parent 63e6d1daed
commit 48a4b43640
3 changed files with 35 additions and 0 deletions

View File

@ -173,6 +173,14 @@ an array and retains its original keys.
lume.filter({1, 2, 3, 4}, function(x) return x % 2 == 0 end) -- Returns {2, 4}
```
### lume.reject(t, fn [, retainkeys])
The opposite of `lume.filter()`: Calls `fn` on each value of `t` table; returns
a new table with only the values where `fn` returned false. If `retainkeys` is
true the table is not treated as an array and retains its original keys.
```lua
lume.filter({1, 2, 3, 4}, function(x) return x % 2 == 0 end) -- Returns {1, 3}
```
### lume.merge(...)
Returns a new table with all the given tables merged together. If a key exists
in multiple tables the right-most table's value is used.

View File

@ -287,6 +287,23 @@ function lume.filter(t, fn, retainkeys)
end
function lume.reject(t, fn, retainkeys)
fn = iteratee(fn)
local iter = getiter(t)
local rtn = {}
if retainkeys then
for k, v in iter(t) do
if not fn(v) then rtn[k] = v end
end
else
for k, v in iter(t) do
if not fn(v) then rtn[#rtn + 1] = v end
end
end
return rtn
end
function lume.merge(...)
local rtn = {}
for i = 1, select("#", ...) do

View File

@ -253,6 +253,16 @@ tests["lume.filter"] = function()
testeq( t, {{ x=1, y=1 }, {x=1, y=3}} )
end
-- lume.reject
tests["lume.reject"] = function()
local t = lume.reject({1, 2, 3, 4, 5}, function(x) return x % 2 == 0 end )
testeq( t, {1, 3, 5} )
local t = lume.reject({a=1, b=2, c=3}, function(x) return x == 2 end, true)
testeq( t, {a=1, c=3} )
local t = lume.reject({{ x=1, y=1 }, { x=2, y=2 }, { x=1, y=3 }}, { x = 1 })
testeq( t, {{ x=2, y=2 }} )
end
-- lume.merge
tests["lume.merge"] = function()
testeq( lume.merge(), {} )