Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hs.fnutils.reduce takes an optional initial value #3363

Merged
merged 1 commit into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions extensions/fnutils/fnutils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -225,27 +225,34 @@ function fnutils.mapCat(t, fn)
return nt
end

--- hs.fnutils.reduce(table, fn) -> table
--- hs.fnutils.reduce(table, fn[, initial]) -> table
--- Function
--- Reduce a table to a single element, using a function
---
--- Parameters:
--- * table - A table containing some sort of data
--- * fn - A function that takes two parameters, which will be elements of the supplied table. It should choose one of these elements and return it
--- * initial - If given, the first call to fn will be with this value and the first element of the table
---
--- Returns:
--- * The element of the supplied table that was chosen by the iterative reducer function
---
--- Notes:
--- * table cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4)
--- * The first iteration of the reducer will call fn with the first and second elements of the table. The second iteration will call fn with the result of the first iteration, and the third element. This repeats until there is only one element left
function fnutils.reduce(t, fn)
function fnutils.reduce(t, fn, ...)
local rest = {...}
local len = #t
if len == 0 then return nil end
if len == 1 then return t[1] end

local result = t[1]
for i = 2, #t do
local start, result
if #rest == 0 then
if len == 0 then return nil end
result = t[1]
start = 2
else
result = rest[1]
start = 1
end
for i = start, len do
result = fn(result, t[i])
end
return result
Expand Down
10 changes: 10 additions & 0 deletions extensions/fnutils/test_fnutils.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function test_reduce()
local reduce = hs.fnutils.reduce

assert(reduce({}, function(x, y) return x + y end) == nil)
assert(reduce({}, function(x, y) return x + y end, 10) == 10)
assert(reduce({1}, function(x, y) return x + y end) == 1)
assert(reduce({1}, function(x, y) return x + y end, 10) == 11)
assert(reduce({1, 2}, function(x, y) return x + y end) == 3)
assert(reduce({1, 2}, function(x, y) return x + y end, 10) == 13)
end