From 48a4b43640850cbf83de9d13c64fd617e966e99c Mon Sep 17 00:00:00 2001 From: rxi Date: Fri, 20 Feb 2015 19:22:42 +0000 Subject: [PATCH] Added lume.reject(), updated tests and README.md --- README.md | 8 ++++++++ lume.lua | 17 +++++++++++++++++ test/test_lume.lua | 10 ++++++++++ 3 files changed, 35 insertions(+) diff --git a/README.md b/README.md index 616363a..3d21b5e 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/lume.lua b/lume.lua index eed4927..e17faca 100644 --- a/lume.lua +++ b/lume.lua @@ -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 diff --git a/test/test_lume.lua b/test/test_lume.lua index 392cb0b..22d7484 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -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(), {} )