Skip to content

Commit 241f3bc

Browse files
committed
implements the key_by utility function
1 parent 24e27c5 commit 241f3bc

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/array/init.lua

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,20 @@ array = {
652652
local mapped = array.map(obj, callback)
653653

654654
return array.flat(mapped)
655+
end,
656+
657+
-- Creates a new table composed of keys generated from the results of running each element of the given table through the given callback
658+
-- @param obj {table}
659+
-- @param callback {function}
660+
-- @return {table}
661+
key_by = function(obj, callback)
662+
utils.raises_error(array, obj, 'key_by')
663+
664+
return array.reduce(obj, function(accumulator, current)
665+
local key = callback(current)
666+
accumulator[key] = current
667+
return accumulator
668+
end, {})
655669
end
656670
}
657671

test.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,3 +434,15 @@ test('flat_map', function(a)
434434
{ 1, 2, 2, 4, 3, 6 }
435435
)
436436
end)
437+
438+
test('key_by', function(a)
439+
a.deep_equal(
440+
array.key_by({ { id = 1, name = 'lua' }, { id = 2, name = 'javascript' } }, function(item)
441+
return item.id
442+
end),
443+
{
444+
[1] = { id = 1, name = 'lua' },
445+
[2] = { id = 2, name = 'javascript' }
446+
}
447+
)
448+
end)

0 commit comments

Comments
 (0)