diff --git a/lua/plenary/functional.lua b/lua/plenary/functional.lua index 6a5b3673..43c19f7a 100644 --- a/lua/plenary/functional.lua +++ b/lua/plenary/functional.lua @@ -40,7 +40,7 @@ function f.any(fun, iterable) end function f.all(fun, iterable) - for k, v in pairs(iterable) do + for k, v in ipairs(iterable) do if not fun(k, v) then return false end @@ -48,7 +48,6 @@ function f.all(fun, iterable) return true end - function f.if_nil(val, was_nil, was_not_nil) if val == nil then return was_nil diff --git a/tests/plenary/functional_spec.lua b/tests/plenary/functional_spec.lua index 9a34b226..41d273cd 100644 --- a/tests/plenary/functional_spec.lua +++ b/tests/plenary/functional_spec.lua @@ -15,4 +15,44 @@ describe("functional", function() assert.is.equal(expected, f.partial(args, 1, 2, 3, 4)()) end) end) -end) + + describe("all", function() + it("returns true when all elements satisfy predicate", function() + assert.is_true(f.all(function(_, x) return x < 10 end, {1, 2, 3, 4})) + end) + + it("returns false if any element fails predicate", function() + assert.is_false(f.all(function(_, x) return x < 10 end, {1, 2, 30, 4})) + end) + + it("returns true on empty list", function() + assert.is_true(f.all(function(_, x) return false end, {})) + end) + end) + + describe("any", function() + it("returns true if any element satisfies predicate", function() + assert.is_true(f.any(function(_, v) return v > 10 end, {1, 2, 12, 4})) + end) + + it("returns false when no elements match", function() + assert.is_false(f.any(function(_, v) return v > 10 end, {1, 2, 3, 4})) + end) + + it("returns false on empty list", function() + assert.is_false(f.any(function(_, v) return true end, {})) + end) + end) + + describe("if_nil", function() + it("returns was_nil value if nil", function() + assert.equals("fallback", f.if_nil(nil, "fallback", "not nil")) + end) + + it("returns was_not_nil value if not nil", function() + assert.equals("not nil", f.if_nil(5, "fallback", "not nil")) + end) + end) + end) + +