Skip to content

Commit

Permalink
implements the key_by utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
EvandroLG committed Jan 10, 2024
1 parent 24e27c5 commit 241f3bc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/array/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,20 @@ array = {
local mapped = array.map(obj, callback)

return array.flat(mapped)
end,

-- Creates a new table composed of keys generated from the results of running each element of the given table through the given callback
-- @param obj {table}
-- @param callback {function}
-- @return {table}
key_by = function(obj, callback)
utils.raises_error(array, obj, 'key_by')

return array.reduce(obj, function(accumulator, current)
local key = callback(current)
accumulator[key] = current
return accumulator
end, {})
end
}

Expand Down
12 changes: 12 additions & 0 deletions test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,15 @@ test('flat_map', function(a)
{ 1, 2, 2, 4, 3, 6 }
)
end)

test('key_by', function(a)
a.deep_equal(
array.key_by({ { id = 1, name = 'lua' }, { id = 2, name = 'javascript' } }, function(item)
return item.id
end),
{
[1] = { id = 1, name = 'lua' },
[2] = { id = 2, name = 'javascript' }
}
)
end)

0 comments on commit 241f3bc

Please sign in to comment.