Skip to content

Commit 24e27c5

Browse files
committed
creates a flat_map function
1 parent 783f71b commit 24e27c5

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/array/init.lua

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,17 @@ array = {
641641
end
642642

643643
return output
644+
end,
645+
646+
-- Returns a new array-like table by applying a given callback to each element of the table, and then flattening the result by one level
647+
-- @param obj {table}
648+
-- @param callback {function}
649+
-- @return {table}
650+
flat_map = function(obj, callback)
651+
utils.raises_error(array, obj, 'flat_map')
652+
local mapped = array.map(obj, callback)
653+
654+
return array.flat(mapped)
644655
end
645656
}
646657

test.lua

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,3 +425,12 @@ test('chunk', function(a)
425425
}
426426
)
427427
end)
428+
429+
test('flat_map', function(a)
430+
a.deep_equal(
431+
array.flat_map({ 1, 2, 3 }, function(value)
432+
return { value, value * 2 }
433+
end),
434+
{ 1, 2, 2, 4, 3, 6 }
435+
)
436+
end)

0 commit comments

Comments
 (0)