Skip to content

Commit f6232cf

Browse files
committed
improve remove method
1 parent 009385c commit f6232cf

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

array.lua

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ array = {
429429
-- @value {*}
430430
-- @start_or_finish {number}
431431
-- @finish {number}
432-
-- @returns table
432+
-- @returns {table}
433433
fill = function(value, start_or_finish, finish)
434434
local output = {}
435435
local item = value
@@ -448,6 +448,11 @@ array = {
448448
return output
449449
end,
450450

451+
-- Remove all elements from table that @callback returns thruthy for
452+
-- and returns a new table with the removed items
453+
-- @obj {table}
454+
-- @callback {function}
455+
-- @returns {@table}
451456
remove = function(obj, callback)
452457
local output = {}
453458
local copy = array.deep_copy(obj)
@@ -457,6 +462,8 @@ array = {
457462

458463
if callback(value, i) then
459464
table.insert(output, value)
465+
local index = array.index_of(obj, value)
466+
table.remove(obj, index)
460467
end
461468
end
462469

test.lua

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,12 +315,16 @@ test('fill should create a table using the value passed by argument from start t
315315
a.equal(result[4], value)
316316
end)
317317

318-
test('remove should return a new table with all elements from table that callback returns truthy for', function(a)
318+
test('remove should delete items that callback returns thruthy and should return a new table with the removed items', function(a)
319319
local list = { 1, 2, 3, 4 }
320320
local result = array.remove(list, function(value)
321321
return math.fmod(value, 2) == 0
322322
end)
323323

324+
a.equal(#list, 2)
325+
a.equal(list[1], 1)
326+
a.equal(list[2], 3)
327+
324328
a.equal(#result, 2)
325329
a.equal(result[1], 2)
326330
a.equal(result[2], 4)

0 commit comments

Comments
 (0)