From 241f3bc6d7ebe47a6fb775b6b63f716a2a35ea2f Mon Sep 17 00:00:00 2001 From: Evandro Leopoldino Goncalves Date: Wed, 10 Jan 2024 22:24:22 +0100 Subject: [PATCH] implements the key_by utility function --- src/array/init.lua | 14 ++++++++++++++ test.lua | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/array/init.lua b/src/array/init.lua index c4774bc..020d3db 100644 --- a/src/array/init.lua +++ b/src/array/init.lua @@ -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 } diff --git a/test.lua b/test.lua index 79dce65..d0fc2dc 100644 --- a/test.lua +++ b/test.lua @@ -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)