From 51189d190ddb96acc3d48a03d879d872ece58c75 Mon Sep 17 00:00:00 2001 From: rxi Date: Thu, 6 Mar 2014 19:33:13 +0000 Subject: [PATCH] Made `first` argument in lume.reduce() optional --- README.md | 10 ++++++---- lume.lua | 6 ++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a54cdb8..fdc4ce1 100644 --- a/README.md +++ b/README.md @@ -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.reduce(t, fn, first) +### lume.reduce(t, fn [, first]) 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 -intialised to the `first` value. +left to right, so as to reduce the array to a single value. If a `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 -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]) diff --git a/lume.lua b/lume.lua index 21dfff8..4ef2d11 100644 --- a/lume.lua +++ b/lume.lua @@ -119,8 +119,10 @@ end function lume.reduce(t, fn, first) - for i = 1, #t do first = fn(first, t[i]) end - return first + local acc = first or t[1] + 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