summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWilliam Boman <william@redwill.se>2022-12-19 11:41:58 +0100
committerGitHub <noreply@github.com>2022-12-19 10:41:58 +0000
commit582fe9e53f192f7062c5811153916189e2301f23 (patch)
treed87d134bc9db2df9937901fb948f42b23c8270ae
parentfix(functional): spread function args in _.apply (#770) (diff)
downloadmason-582fe9e53f192f7062c5811153916189e2301f23.tar
mason-582fe9e53f192f7062c5811153916189e2301f23.tar.gz
mason-582fe9e53f192f7062c5811153916189e2301f23.tar.bz2
mason-582fe9e53f192f7062c5811153916189e2301f23.tar.lz
mason-582fe9e53f192f7062c5811153916189e2301f23.tar.xz
mason-582fe9e53f192f7062c5811153916189e2301f23.tar.zst
mason-582fe9e53f192f7062c5811153916189e2301f23.zip
feat(functional): add list.reduce (#772)
-rw-r--r--lua/mason-core/functional/init.lua1
-rw-r--r--lua/mason-core/functional/list.lua12
-rw-r--r--tests/mason-core/functional/list_spec.lua11
3 files changed, 24 insertions, 0 deletions
diff --git a/lua/mason-core/functional/init.lua b/lua/mason-core/functional/init.lua
index dbb27ddd..ee185e8b 100644
--- a/lua/mason-core/functional/init.lua
+++ b/lua/mason-core/functional/init.lua
@@ -61,6 +61,7 @@ _.partition = list.partition
_.take = list.take
_.drop = list.drop
_.drop_last = list.drop_last
+_.reduce = list.reduce
---@module "mason-core.functional.relation"
local relation = lazy_require "mason-core.functional.relation"
diff --git a/lua/mason-core/functional/list.lua b/lua/mason-core/functional/list.lua
index 7c66ccac..8c216c4d 100644
--- a/lua/mason-core/functional/list.lua
+++ b/lua/mason-core/functional/list.lua
@@ -257,4 +257,16 @@ _.drop_last = fun.curryN(function(n, list)
return result
end, 2)
+---@generic T, U
+---@param fn fun(acc: U, item: T): U
+---@param acc U
+---@param list T[]
+---@return U
+_.reduce = fun.curryN(function(fn, acc, list)
+ for i = 1, #list do
+ acc = fn(acc, list[i])
+ end
+ return acc
+end, 3)
+
return _
diff --git a/tests/mason-core/functional/list_spec.lua b/tests/mason-core/functional/list_spec.lua
index a53da4ac..7c3d8cfb 100644
--- a/tests/mason-core/functional/list_spec.lua
+++ b/tests/mason-core/functional/list_spec.lua
@@ -253,4 +253,15 @@ describe("functional: list", function()
assert.same({ "First", "Second", "Third", "I", "Have", "Poor", "Imagination" }, _.drop_last(0, list))
assert.same({}, _.drop_last(10000, list))
end)
+
+ it("should reduce lists", function()
+ local add = spy.new(_.add)
+ assert.equals(15, _.reduce(add, 0, { 1, 2, 3, 4, 5 }))
+ assert.spy(add).was_called(5)
+ assert.spy(add).was_called_with(0, 1)
+ assert.spy(add).was_called_with(1, 2)
+ assert.spy(add).was_called_with(3, 3)
+ assert.spy(add).was_called_with(6, 4)
+ assert.spy(add).was_called_with(10, 5)
+ end)
end)