From c3c2d31d375708d767995c75a26a86324b7d2b64 Mon Sep 17 00:00:00 2001 From: rxi Date: Tue, 24 Feb 2015 21:01:03 +0000 Subject: [PATCH] Changed lume.reduce() to support non-array tables, updated tests --- lume.lua | 15 ++++++++++++--- test/test_lume.lua | 3 +++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/lume.lua b/lume.lua index 99e4550..a02a7d5 100644 --- a/lume.lua +++ b/lume.lua @@ -259,9 +259,18 @@ end function lume.reduce(t, fn, 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 + local acc = first + local started = first and true or false + local iter = getiter(t) + for k, v in iter(t) do + if started then + acc = fn(acc, v) + else + acc = v + started = true + end + end + assert(started, "reduce of an empty table with no first value") return acc end diff --git a/test/test_lume.lua b/test/test_lume.lua index 22d7484..2d0dd1a 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -230,6 +230,9 @@ tests["lume.reduce"] = function() testeq( lume.reduce({1, 2, 3, 4}, add, 5), 15 ) testeq( lume.reduce({1}, add), 1 ) testeq( lume.reduce({}, concat, "potato"), "potato" ) + testeq( lume.reduce({a=1, b=2}, add, 5), 8 ) + testeq( lume.reduce({a=1, b=2}, add), 3 ) + tester.test.error(lume.reduce, {}, add) end -- lume.set