Skip to content

Commit 6124cb4

Browse files
committed
create sum method
1 parent 5634921 commit 6124cb4

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

array.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,18 @@ array = {
222222
return _memo
223223
end,
224224

225+
-- Return the sum of the values in table
226+
-- @obj {table}
227+
-- @callback {function}
228+
-- @returns {number}
229+
sum = function(obj)
230+
raises_error(array, obj, 'sum')
231+
232+
return array.reduce(obj, function(memo, value)
233+
return memo + value
234+
end)
235+
end,
236+
225237
-- Return a new table joining all values from the two tables passed by parameter
226238
-- @obj {table}
227239
-- @obj2 {table}

test.lua

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

149+
test('sum should return sum of the values in table', function(a)
150+
local result = array.sum({10, 20, 30, 40, 50})
151+
a.equal(result, 150)
152+
end)
153+
149154
test('index_of should return correct position of value in the table', function(a)
150155
a.equal(array.index_of({ 20, 30, 40, 50 }, 40), 3)
151156
end)

0 commit comments

Comments
 (0)