Made first argument in lume.reduce() optional

This commit is contained in:
rxi 2014-03-06 19:33:13 +00:00
parent e6d47627cd
commit 51189d190d
2 changed files with 10 additions and 6 deletions

View File

@ -105,12 +105,14 @@ supplied it is called on each value, true is returned if any of the calls to
lume.any({1, 2, 1}, function(x) return x == 1 end) -- Returns true lume.any({1, 2, 1}, function(x) return x == 1 end) -- Returns true
``` ```
### lume.reduce(t, fn, first) ### lume.reduce(t, fn [, first])
Applies `fn` on two arguments cumulative to the items of the array `t`, from Applies `fn` on two arguments cumulative to the items of the array `t`, from
left to right, so as to reduce the array to a single value. The accumulator is left to right, so as to reduce the array to a single value. If a `first` value
intialised to the `first` value. is specified the accumulator is initialised to this, otherwise the first value
in the array is used. If the array is empty and no `first` value is specified
an error is raised,
```lua ```lua
lume.reduce({1, 2, 3}, function(a, b) return a + b end, 0) -- Returns 6 lume.reduce({1, 2, 3}, function(a, b) return a + b end) -- Returns 6
``` ```
### lume.set(t [, retainkeys]) ### lume.set(t [, retainkeys])

View File

@ -119,8 +119,10 @@ end
function lume.reduce(t, fn, first) function lume.reduce(t, fn, first)
for i = 1, #t do first = fn(first, t[i]) end local acc = first or t[1]
return first assert(acc, "reduce of an empty array with no first value")
for i = first and 1 or 2, #t do acc = fn(acc, t[i]) end
return acc
end end