Skip to content

Commit

Permalink
hs.fnutils.reduce takes an optional initial value
Browse files Browse the repository at this point in the history
This is in line with the reduce function in other languages like JavaScript, Python, and Ruby.
  • Loading branch information
knu authored and cmsj committed Feb 7, 2023
1 parent 92f2902 commit fe03502
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
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

0 comments on commit fe03502

Please sign in to comment.