Skip to content

Commit cbd8d49

Browse files
committed
create reduce_right method
1 parent f6232cf commit cbd8d49

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

array.lua

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,29 @@ array = {
224224
return _memo
225225
end,
226226

227+
-- This function is like reduce except that it interates over table's elements from right to left
228+
-- @obj {table}
229+
-- @callback {function}
230+
-- @memo {*}
231+
-- @returns {*}
232+
reduce_right = function(obj, callback, memo)
233+
raises_error(array, obj, 'reduce_right')
234+
235+
local initialIndex = #obj
236+
local _memo = memo
237+
238+
if _memo == nil then
239+
initialIndex = initialIndex - 1
240+
_memo = obj[#obj]
241+
end
242+
243+
for i=initialIndex, 1, -1 do
244+
_memo = callback(_memo, obj[i], i)
245+
end
246+
247+
return _memo
248+
end,
249+
227250
-- Return the sum of the values in table
228251
-- @obj {table}
229252
-- @callback {function}

test.lua

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,14 @@ test('reduce should concatenate all items', function(a)
146146
a.equal(result, 'abcde')
147147
end)
148148

149+
test('reduce_right should concatenate all items starting from right to left', function(a)
150+
local result = array.reduce_right({ 'a', 'b', 'c', 'd', 'e' }, function(memo, value)
151+
return memo .. value
152+
end)
153+
154+
a.equal(result, 'edcba')
155+
end)
156+
149157
test('sum should return sum of the values in table', function(a)
150158
local result = array.sum({10, 20, 30, 40, 50})
151159
a.equal(result, 150)

0 commit comments

Comments
 (0)