Skip to content

Implementing the groupBy #1108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions doc/_stdlib_gen/stdlib-content.jsonnet
Original file line number Diff line number Diff line change
@@ -1432,6 +1432,16 @@ local html = import 'html.libsonnet';
|||,
]),
},
{
name: 'groupBy',
params: ['arr', 'keyF', 'onEmpty'],
availableSince: 'upcoming',
description: html.paragraphs([
|||
Return an object composed of keys generated from the results of running each element of <code>arr</code> through <code>function</code>.
|||,
]),
},
],
},
{
9 changes: 9 additions & 0 deletions stdlib/std.jsonnet
Original file line number Diff line number Diff line change
@@ -1741,6 +1741,15 @@ limitations under the License.
a;
std.foldl(maxFn, arr, maxVal),

groupBy(arr, keyF=id)::
local foldf(o, e, f) =
local k = std.toString(f(e));
if std.objectHas(o, k) then
c + {[k]: o[k] + [e]}
else
o + {[k]: [e]};
std.foldl(function(o, e) foldf(o, e, f), arr, {});

xor(x, y):: x != y,

xnor(x, y):: x == y,
3 changes: 2 additions & 1 deletion test_suite/stdlib.jsonnet
Original file line number Diff line number Diff line change
@@ -1560,6 +1560,7 @@ std.assertEqual(std.maxArray([1, 2, 3]), 3) &&
std.assertEqual(std.maxArray(['1', '2', '3']), '3') &&
std.assertEqual(std.maxArray(['a', 'x', 'z']), 'z') &&

std.assertEqual(std.groupBy([1, 1.5, 2, 3], std.floor), { '1': [1, 1.5], '2': [2], '3': [3] }) &&

std.assertEqual(std.xor(true, false), true) &&
std.assertEqual(std.xor(true, true), false) &&
@@ -1597,6 +1598,6 @@ std.assertEqual(std.trim('already trimmed string'), 'already trimmed string') &&
std.assertEqual(std.trim(' string with spaces on both ends '), 'string with spaces on both ends') &&
std.assertEqual(std.trim('string with newline character at end\n'), 'string with newline character at end') &&
std.assertEqual(std.trim('string with tabs at end\t\t'), 'string with tabs at end') &&
std.assertEqual(std.trim('string with other special whitespaces at end\f\r\u0085\u00A0'), 'string with carriage return at end') &&
std.assertEqual(std.trim('string with other special whitespaces at end\f\r\u0085 '), 'string with carriage return at end') &&

true